我有这个路径/ user / shared / name / Documents。 在文档里面有子文件夹和文件。
通过使用Java swing,如何仅在给定路径中获取所有子文件夹名称? 然后单击导出按钮并生成路径值的文本文件。
Example.txt:
path /Users/User1/Desktop/arc_testing 2/
Directory:/Users/User1/Desktop/arc_testing 2/099923
----Directory:/Users/User1/Desktop/arc_testing 2/099923/000_Fonts
----Directory:/Users/User1/Desktop/arc_testing 2/099923/000_Fonts/fancybox
----Directory:/Users/User1/Desktop/arc_testing 2/099923/010_Correspondence
----Directory:/Users/User1/Desktop/arc_testing 2/099923/010_Correspondence/smart
Directory:/Users/User1/Desktop/arc_testing 2/099924
----Directory:/Users/User1/Desktop/arc_testing 2/099924/000_Fonts
----Directory:/Users/User1/Desktop/arc_testing 2/099924/000_Fonts/fancybox
----Directory:/Users/User1/Desktop/arc_testing 2/099924/010_Correspondence
----Directory:/Users/User1/Desktop/arc_testing 2/099924/010_Correspondence/smart
----Directory:/Users/User1/Desktop/arc_testing 2/099924/010_Correspondence/smart/images
----Directory:/Users/User1/Desktop/arc_testing 2/099924/010_Correspondence/smart/js
----Directory:/Users/User1/Desktop/arc_testing 2/099924/010_Correspondence/smart/services
----Directory:/Users/User1/Desktop/arc_testing 2/099924/010_Correspondence/smart/styles
Directory:/Users/User1/Desktop/arc_testing 2/099925
Directory:/Users/User1/Desktop/arc_testing 2/099926/020_Supplied
----Directory:/Users/User1/Desktop/arc_testing 2/099925/020_Supplied/doc
----Directory:/Users/User1/Desktop/arc_testing 2/099925/020_Supplied/font
----Directory:/Users/User1/Desktop/arc_testing 2/099925/020_Supplied/makefont
----Directory:/Users/User1/Desktop/arc_testing 2/099925/020_Supplied/pdf-ok
----Directory:/Users/User1/Desktop/arc_testing 2/099925/020_Supplied/tutorial
答案 0 :(得分:-1)
如果您使用的是Java 8,请查看有用的方法Stream walk(Path start, FileVisitOption... options)
通过遍历以给定起始文件为根的文件树,返回使用Path延迟填充的Stream。文件树遍历深度优先,流中的元素是Path对象,它们就像通过解析相对路径来获得一样。
另请参阅此问题:How do I iterate through the files in a directory in Java?
Oracle有很好的教程:Walking the File Tree
以下是遍历文件系统的示例:
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FileTreeExample {
private static final String START_PATH = "/home/xxx/dev/python";
public static void main(String[] args) throws IOException {
Files.walk(Paths.get(START_PATH))
.map(Path::toFile)
.filter(File::isDirectory)
.map(File::getAbsolutePath)
.forEach(System.out::println); // or write it to file
}
}
结果:
/家庭/ XXX的/ dev /蟒 /家庭/ XXX的/ dev /蟒蛇/ mongo_tutorial /家庭/ XXX的/ dev /蟒蛇/ mongo_tutorial /蒙戈 /家庭/ XXX的/ dev /蟒/ mongo_tutorial /蒙戈/的 pycache 强> /home/xxx/dev/python/mongo_tutorial/.idea /home/xxx/dev/python/mongo_tutorial/.idea/dictionaries /家庭/ XXX的/ dev /蟒蛇/ pyminds /家庭/ XXX的/ dev /蟒蛇/ pyminds /消息 /家庭/ XXX的/ dev /蟒蛇/ pyminds /结果 /home/xxx/dev/python/pyminds/.idea /家庭/ XXX的/ dev /蟒/ pyminds /的 pycache 强> /家庭/ XXX的/ dev /蟒蛇/ bforce /家庭/ XXX的/ dev /蟒/垃圾