【问题标题】:Files walk doesnt return absolute paths only filename文件步行不返回绝对路径只返回文件名
【发布时间】:2019-04-27 14:09:15
【问题描述】:

我的桌面中有一个文件夹,其结构类似于:

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

【问题讨论】:

  • 文件夹'documents'的实际绝对路径是什么?
  • @BlackPearl C:\Users\santi\Desktop\documents
  • 我试过你的代码,我得到了正确的绝对路径。除非您在该路径中选择一个文件,否则您不会得到C:\Users\n\workspace\test\1.html。你只想要/documents/00/2.html 而不是C:\Users\santi\Desktop\/documents/00/2.html 吗?
  • @BlackPearl 是的,我想要完整路径 C:\Users\santi\Desktop\documents\00\1.html

标签: java swing arraylist nio jfilechooser


【解决方案1】:

尝试使用p.toString(),而不是使用p.getFileName().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]

这是您期望的输出吗?

【讨论】:

    猜你喜欢
    • 2011-07-02
    • 1970-01-01
    • 2021-06-07
    • 2011-02-12
    • 2012-03-14
    • 1970-01-01
    • 2022-11-25
    • 2015-08-15
    • 2020-01-10
    相关资源
    最近更新 更多