gpt4 book ai didi

java - 文件遍历不返回绝对路径,仅返回文件名

转载 作者:行者123 更新时间:2023-12-02 01:32:07 24 4
gpt4 key购买 nike

我的桌面上有一个文件夹,其结构与此类似:

-/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]

这是您期望的输出吗?

关于java - 文件遍历不返回绝对路径,仅返回文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55881389/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com