I have a jar compiled with the input files needed to run the jar within the jar itself. Question is, how do I specify the path so that the files can be read?
This is how I try to read the files:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null) {
classLoader = getClass().getClassLoader();
}
System.out.println("FILE is readable? -> " + new File(classLoader.getResource(strFileName).toExternalForm()).canRead());
List<String> lines = Files.readAllLines(new File(classLoader.getResource(strFileName).toExternalForm()).toPath());
But always, I get the message that the file is not readable. I know the file is in there because I've checked. I also know the classloader is finding the file because if I give it the file input.txt
as strFileName
, the path it produces points to within the jar and is similar to: jar:file:/home/me/Dropbox/Assignments/Files/MyJar.jar!/input.txt
. Because of this, I know it finds the file, but then some io error occurs, and I'm just not sure what the problem is.
java.nio.file.NoSuchFileException: jar:file:/home/me/Dropbox/Assignments/Files/MyJar.jar!/input.txt
at sun.nio.fs.UnixException.translateToIOException(UnixException.java:86)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107)
at sun.nio.fs.UnixFileSystemProvider.newByteChannel(UnixFileSystemProvider.java:214)
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.readAllLines(Files.java:3202)
at java.nio.file.Files.readAllLines(Files.java:3242)
at com.smac89.school.Program.readState(GameState.java:203)
at com.smac89.school.Program.simulate(GameState.java:57)
at com.smac89.school.Program.main(GameState.java:31)
How do I do this? I have tried all manner of tricks and I still can't get the program to read the file.