如何在下面给出的程序中获取/生成文件对象

时间:2013-07-31 07:18:46

标签: java

我是java中的蚕食。我有自己的努力来完成这些事情。但我当然面临挑战。我有一个虚拟程序,用于搜索作为命令行参数提供的特定扩展名(.txt)的文件。我正在尝试制作这些搜索文件的文件对象以供进一步操作。但我无法理解如何在我的代码中执行此操作..这是我的代码示例...

public class Find {

public static class Finder extends SimpleFileVisitor<Path> {

    private final PathMatcher matcher;
    private int numMatches = 0;

    Finder(String pattern) {
        matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
    }

     void find(Path file) {
        Path name = file.getFileName();
        if (name != null && matcher.matches(name)) {
            numMatches++;
            System.out.println(file);
        }
    }

    // Prints the total number of
    // matches to standard out.
    void done() {
        System.out.println("Matched: "+ numMatches);
    }

    // Invoke the pattern matching
    // method on each file.
    //@Override
    public FileVisitResult visitFile(Path file,
            BasicFileAttributes attrs) {
        find(file);
        return CONTINUE;
    }

    // Invoke the pattern matching
    // method on each directory.
    //@Override
    public FileVisitResult preVisitDirectory(Path dir,
            BasicFileAttributes attrs) {
        find(dir);
        return CONTINUE;
    }

    //@Override
    public FileVisitResult visitFileFailed(Path file, IOException exc) {
        System.err.println(exc);
        return CONTINUE;
    }
}


public static void main(String[] args) throws IOException {

    Iterable<Path> root;
    root = FileSystems.getDefault().getRootDirectories();
   // System.out.println(name.getAbsolutePath());
    for (Path startingDir : FileSystems.getDefault().getRootDirectories()) {
       String pattern = args[0];

        Finder finder = new Finder(pattern);
        Files.walkFileTree(startingDir, finder);

    }
}

}

1 个答案:

答案 0 :(得分:0)

这是我想要做的。我的程序的输出是一长串文本文件及其绝对路径。现在我想制作这些文件的对象,以便我可以将这些文件上传到URL。上传它们我必须制作一个文件对象流将被发送..如何获取absoluteFilename?为了得到这个你必须有一个文件对象...正确....我修改的问题是:如何使搜索文件的文件对象???

FileInputStream fileInputStream = null;

    try {
        new FileInputStream("absoluteFilename");

        byte[] buffer = new byte[MAX_SIZE];
        int bufferIndex = 0;
        while (fileInputStream.available() > 0) {
            buffer[bufferIndex++] = (byte) fileInputStream.read();
        }
        byte[] fileContent = new byte[bufferIndex];
        System.arraycopy(buffer,0,fileContent,0,bufferIndex);

        URL serverUrl = new URL(url);
        URLConnection connection = serverURL.openConnection();
        connection.setConnectTimeout(60000);
        connection.getOutputStream().write(fileContent);

    } catch (Exception fatal) {
        //proper handling??