Rah*_*hra 3 java filenotfoundexception maven java-8 nosuchfileexception
我为这个看似简单且几乎是一个愚蠢的问题道歉,但我花了很多时间来修复它而没有太大的成功.
我创建了一个非常简单的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);
}
}
Run Code Online (Sandbox Code Playgroud)
我得到的例外:
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
Run Code Online (Sandbox Code Playgroud)
这似乎是一个非常愚蠢的问题,但我无法理解它.任何帮助都是真诚的感谢.
您正在使用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);
Run Code Online (Sandbox Code Playgroud)
请注意,获得它的方式Path真的很复杂.
不幸的是,Class该类没有更新以利用Java 7中引入的java nio API.
如果我们可以编写如下内容,那将会更简单:
Files.lines(App.class.getResourcePath("/test.txt"))
.forEach(System.out::println);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
992 次 |
| 最近记录: |