3

对于这个看似简单且几乎是愚蠢的问题,我深表歉意,但我花了很多时间来解决它,但没有取得多大成功。

我创建了一个非常简单的 Maven 项目,然后在src/resources这样的文件夹中创建了一个简单的文本文件。

在此处输入图像描述

在此处输入图像描述

pom.xml 很简单。该类App如下所示:

public class App {
    public static void main(String[] args) throws IOException {
        Files.lines(Paths.get("test.txt")).forEach(System.out::println);
    }
}

我得到的例外是:

Exception in thread "main" java.nio.file.NoSuchFileException: test.txt
    at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:79)
    at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97)
    at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:102)
    at sun.nio.fs.WindowsFileSystemProvider.newByteChannel(WindowsFileSystemProvider.java:230)
    at java.nio.file.Files.newByteChannel(Files.java:361)
    at java.nio.file.Files.newByteChannel(Files.java:407)
    at java.nio.file.spi.FileSystemProvider.newInputStream(FileSystemProvider.java:384)
    at java.nio.file.Files.newInputStream(Files.java:152)
    at java.nio.file.Files.newBufferedReader(Files.java:2784)
    at java.nio.file.Files.lines(Files.java:3744)
    at java.nio.file.Files.lines(Files.java:3785)
    at com.rahul.App.main(App.java:12)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

Process finished with exit code 1

这似乎是一个非常愚蠢的问题,但我无法理解它。真诚感谢任何帮助。

4

2 回答 2

7

您正在使用 Maven,并且要加载的文本文件已正确放置在类路径中:src/main/resources。问题是 Paths.get("test.txt")不在类路径中搜索文件,而是在文件系统中搜索文件。

因此,您需要从类路径中获取资源作为 URI 并将其传递给Paths.get(URI)

Path textFile = Paths.get(App.class.getResource("/test.txt").toURI());
Files.lines(textFile).forEach(System.out::println);

请注意,获取的Path方式非常复杂。
不幸的是,Class该类没有更新以利用 Java 7 中引入的 java nio API。
如果我们可以编写如下内容,那将非常简单:

Files.lines(App.class.getResourcePath("/test.txt"))
     .forEach(System.out::println);
于 2018-03-11T16:35:11.943 回答
0

请检查您的test.txt路径。您正在尝试访问您的文件,就像它与您的 Main 类位于同一文件夹中一样。如果您想访问您的文件,您应该使用正确的相对路径。

于 2018-03-11T16:34:48.280 回答