0

我是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);

    }
}

}

4

1 回答 1

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??
于 2013-07-31T07:38:22.240 回答