使用 nio 的路径数组

huangapple go评论57阅读模式
英文:

Array of Path using nio

问题

public class Task01 {
    public static void main(String[] args) throws IOException {
        Path dir = Paths.get("C:\\Users\\......");
        System.out.println(findFile(dir, "Task01.java"));
    }

    public static ArrayList<Path> findFile(Path path, String filename) throws IOException {
        ArrayList<Path> list1 = new ArrayList<>();

        try (DirectoryStream<Path> stream = Files.newDirectoryStream(path, filename)) {
            for (Path entry : stream) {
                if (entry.toFile().isDirectory()) {
                    findFile(entry, filename);
                } else {
                    list1.add(entry.toAbsolutePath());
                }
            }
        }
        return list1;
    }
}
英文:

I'm just studying topic nio and got the following task:
do recursive search of file name using nio. The method should return a list of found Path.
When I run the code below in output I see only [ ]. Could someone explain and correct me?

public class Task01 {
    public static void main(String[] args) throws IOException {
        Path dir = Paths.get(&quot;C:\\Users\\......&quot;);
        System.out.println(findFile(dir, &quot;Task01.java&quot;));
    }

    public static ArrayList&lt;Path&gt; findFile(Path path, String filename) throws IOException {
        Path dir = Paths.get(&quot;C:\\....&quot;);
        ArrayList&lt;Path&gt; list1 = new ArrayList&lt;&gt;();

        try (DirectoryStream&lt;Path&gt; stream = Files.newDirectoryStream(path, filename)) {
            for (Path entry : stream) {
                if (path.toFile().isDirectory()) {
                    findFile(path, filename);
                } else list1.add(entry.toAbsolutePath());
            }

        }
        return list1;
    }
}

答案1

得分: 1

首先,在进行递归时,希望使用 entry 而不是 path,否则您将无法深入进入目录树。

此外,使用 Files.newDirectoryStream(path) 而不是 Files.newDirectoryStream(path, fileNamePattern),第二种方法会在路径中创建一个流,其文件名与 fileNamePattern 匹配,在您的情况下,如果 Test.java 不位于 path 中,它将为空 []

public static void main(String[] args) throws IOException {
    Path dir = Paths.get("E:\\dev\\...");
    System.out.println(findFile(dir, "TestA.java"));
}

public static ArrayList<Path> findFile(Path path, String filename) throws IOException {
    ArrayList<Path> list1 = new ArrayList<>();

    try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) {
        for (Path entry : stream) {
            if (Files.isDirectory(entry)) {
               list1.addAll(findFile(entry, filename));
            } else if(entry.getFileName().endsWith(filename)){
               list1.add(entry.toAbsolutePath());
            }
        }
    }
    return list1;
}
英文:

First of all, when doing the recursion, you want to use entry instead of path, otherwise you are not going down the directory tree.

Also use Files.newDirectoryStream(path) instead of Files.newDirectoryStream(path, fileNamePattern) the second method creates a stream in the path whose filename matches fileNamePattern, in your case it will be empty [] if your Test.java is not located in path

public static void main(String[] args) throws IOException {
    Path dir = Paths.get(&quot;E:\\dev\\...&quot;);
    System.out.println(findFile(dir, &quot;TestA.java&quot;));
}

public static ArrayList&lt;Path&gt; findFile(Path path, String filename) throws IOException {
    ArrayList&lt;Path&gt; list1 = new ArrayList&lt;&gt;();

    try (DirectoryStream&lt;Path&gt; stream = Files.newDirectoryStream(path)) {
        for (Path entry : stream) {
            if (Files.isDirectory(entry)) {
               list1.addAll(findFile(entry, filename));
            } else if(entry.getFileName().endsWith(filename)){
               list1.add(entry.toAbsolutePath());
            }
        }
    }
    return list1;
}

答案2

得分: 1

这段代码可能适用于您:

public static ArrayList<Path> findFile(Path path, String filename) throws IOException {
    ArrayList<Path> list1 = new ArrayList<>();

    try (DirectoryStream<Path> stream = Files.newDirectoryStream(path, filename)) {
        for (Path entry : stream) {
            System.out.println(entry + "-" + entry.getFileName());
            if (Files.isDirectory(entry)) {
                list1.addAll(findFile(entry, filename));
            } else if (entry.getFileName().toString().equals(filename)) {
                list1.add(entry.toAbsolutePath());
            }
        }
    }
    return list1;
}
  • 当将文件名传递给Files.newDirectoryStream(path, filename)时,它将仅在给定的路径中搜索,不会搜索子目录。因此,在此处不应传递文件名以进行过滤。
  • 如果您递归调用方法,还必须确保将返回值向上传递:list1.addAll(findFile(entry, filename));
  • for循环中始终使用entry,而不是path,否则您不会递归处理目录结构。(参见Files.isDirectory(entry),而不是path.toFile().isDirectory()

更新:改进了对java.nio API的使用(感谢@Andreas)。没错,我对nio API了解较少。

英文:

This code may work for you:

public static ArrayList&lt;Path&gt; findFile(Path path, String filename) throws IOException {
    ArrayList&lt;Path&gt; list1 = new ArrayList&lt;&gt;();

    try (DirectoryStream&lt;Path&gt; stream = Files.newDirectoryStream(path,filename)) {
        for (Path entry : stream) {
        	System.out.println(entry+ &quot;-&quot;+entry.getFileName());
            if (Files.isDirectory(entry)) {
            	list1.addAll(findFile(entry, filename));
            } 
            else if (entry.getFileName().toString().equals(filename)) 
            	list1.add(entry.toAbsolutePath());
        }

    }
    return list1;
}
  • When passing filename to Files.newDirectoryStream(path,filename) it will only search in the path itself, no subdirectories. So you may not pass the filename here to filter.
  • if you call your method recursively you must also make sure the return values are passed upwards: list1.addAll(findFile(entry, filename));
  • within the for loop always work with entry, not path otherwise you are not processing your directory structure recursively. (see Files.isDirectory(entry) instead of path.toFile().isDirectory()

UPDATE: improved usage of java.nio API (thanks to @Andreas). It's correct I'm less familiar with the nio api.

huangapple
  • 本文由 发表于 2020年9月22日 23:34:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/64013048.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定