我的桌面上有一个文件夹,其结构类似于:
-/documents
-/00
-1.html
-2.html
-/01
-3.html
-4.html
-/02
-5.html
-6.html
我想获取/documents
中的所有文件,所以我做了这个:
ArrayList<String> paths = new ArrayList<String>();
fc = new JFileChooser();
fc.setMultiSelectionEnabled(true);
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
fc.showOpenDialog(fc);
File[] file = fc.getSelectedFiles();
for (File f : file) {
try {
Files.walk(Paths.get(f.getAbsolutePath())).filter(Files::isRegularFile)
.forEach(p -> paths.add(p.getFileName().toString()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return paths;
但是我只得到文件名,如下所示:
1.html
2.html
等等我无法找到像这样获取每个文件路径的方法:
/documents/00/1.html
/documents/00/2.html
/documents/01/3.html
/documents/01/4.html
等等。使用p.getFileName().toAbsolutePath()
没有成功,我得到的路径就像它们在我的工作区内:
C:\Users\n\workspace\test\1.html
而不是使用p.getFileName().toString()
尝试使用p.toString()
。你应该得到所有文件的实际路径输出。
我创建了一个类似的结构,如果我运行上面的程序如下:
ArrayList<String> paths = new ArrayList<String>();
JFileChooser fc = new JFileChooser();
fc.setMultiSelectionEnabled(true);
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
fc.showOpenDialog(fc);
File[] file = fc.getSelectedFiles();
for (File f : file) {
System.out.println(f.getAbsolutePath());
try {
Files.walk(Paths.get(f.getAbsolutePath())).filter(Files::isRegularFile)
.forEach(p -> paths.add(p.toString()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(paths);
我得到以下输出:
[D:\ document \ 00 \ 1.html,D:\ document \ 00 \ 2.html,D:\ document \ 01 \ 3.html]
这是您期望的输出吗?