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

标签 java swing arraylist nio jfilechooser

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

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

相关文章:

java - 123.12/23 需要正则表达式模式

java - Java中如何让多个线程操作一个数据对象

java - BigDecimal 值不正确

java - 如何在 Swing 中制作自定义尺寸的组件

java - 获取字体、大小、粗体等

java - Android listView ArrayList 类似搜索

java - 将 arraylist int 转换为字符串

java - 线程对于某些值提前停止

java - 从 JAR 运行 Main.class,在应用程序框架中显示结果

java - 如何将文本文件存储到数组中