Java – cannot use paths Get() loads files from Maven resources
I apologize for this seemingly simple and almost stupid problem, but I spent a lot of time fixing it without much success
I created a very simple Maven project and then created a simple text file in the Src / Resources folder
pom. XML is very simple The app class looks like this:
public class App { public static void main(String[] args) throws IOException { Files.lines(Paths.get("test.txt")).forEach(System.out::println); } }
Exceptions I get:
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
This seems to be a very stupid question, but I can't understand it Any help is a sincere thanks
Solution
You are using maven, and the text file you want to load is correctly placed in the classpath: Src / main / resources The problem is paths Get ("test. TXT") does not search for files in the classpath, but for files in the file system
So what you need is to get the resource from the classpath as URI and pass it to paths get(URI):
Path textFile = Paths.get(App.class.getResource("/test.txt").toURI()); Files.lines(textFile).forEach(System.out::println);
Note that the way to get path is really complex Unfortunately, the class class has not been updated to take advantage of the Java NiO API introduced in Java 7 It would be simpler if we could write the following:
Files.lines(App.class.getResourcePath("/test.txt")) .forEach(System.out::println);