不能使用Files.walk遍历目录

huangapple go评论56阅读模式
英文:

Cannot walk directory using Files.walk

问题

我正在努力理解为什么我的代码无法运行。

以下是使用 java.io 查找路径目录并打印该目录中所有 .txt 文件标题的示例。

我的代码如下:

try 
{
    Files.walk(Paths.get("\\Users\\Name\\Desktop\\Test Folder")).forEach(p -> {
        if (p.getFileName().toString().endsWith(".txt")) {
            System.out.println("Text doc: " + p.getFileName());
        }
    });
} catch (IOException e) {
    e.printStackTrace();
}

我目前正在导入 java.io.IOExceptionjava.nio.file.Filesjava.nio.file.Paths

我得到的错误是 java.nio.file.NoSuchFileException: myDirPath

如果有人能帮忙,或者至少指点我正确的方向,我将非常感谢。

英文:

I am trying to understand why my code won't run.

The example is how to use java.io to find a path directory and print out the title of all .txt files in that directory.

My code is below:

try 
	{
		Files.walk(Paths.get(\\Users\\Name\\Desktop\\Test Folder)).forEach(p -> {
			if (p.getFileName().toString().endsWith(".txt")) {
				System.out.println("Text doc: " + p.getFileName());
			}
		});
	} catch (IOException e) {
		e.printStackTrace();
	}

I am currently importing java.io.IOException, java.nio.file.Files, and java.nio.file.Paths.

The error I am getting is java.nio.file.NoSuchFileException: myDirPath.

If anyone can help, or at least point me in the right direction I would be very grateful.

答案1

得分: 1

尝试
{
    Files.walk(Paths.get("/Users/Jayden/Desktop/Test Folder")).forEach(p -> {
        if (p.getFileName().toString().endsWith(".txt")) {
            System.out.println("文本文档:" + p.getFileName());
        }
    });
} catch (IOException e) {
    e.printStackTrace();
}

我没有正确使用斜杠
英文:
try 
	{
		Files.walk(Paths.get("/Users/Jayden/Desktop/Test Folder")).forEach(p -> {
			if (p.getFileName().toString().endsWith(".txt")) {
				System.out.println("Text doc: " + p.getFileName());
			}
		});
	} catch (IOException e) {
		e.printStackTrace();
	}

I was not using slashes properly.

huangapple
  • 本文由 发表于 2020年9月11日 08:10:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/63839166.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定