java – 无法使用Paths.get()从Maven资源加载文件
发布时间:2020-12-15 08:25:30 所属栏目:Java 来源:网络整理
导读:我为这个看似简单且几乎是一个愚蠢的问题道歉,但我花了很多时间来修复它而没有太大的成功. 我创建了一个非常简单的maven项目,然后在src / resources文件夹中创建了一个简单的文本文件. pom.xml很简单. App类看起来像这样: public class App { public static
我为这个看似简单且几乎是一个愚蠢的问题道歉,但我花了很多时间来修复它而没有太大的成功.
我创建了一个非常简单的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 这似乎是一个非常愚蠢的问题,但我无法理解它.任何帮助都是真诚的感谢. 解决方法
您正在使用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的方式确实很复杂. Files.lines(App.class.getResourcePath("/test.txt")) .forEach(System.out::println); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |