I\'m having trouble reading a text file from inside a jar. I managed it while it was unzipped but now that I\'ve archived it it won\'t work. The jar has:
Assuming you're executing the BTA.jar
, you can use
InputStream in = YourClass.class.getResourceAsStream("/Splash.txt");
to retrieve an InputStream
and pass it to the BufferedReader
through an InputStreamReader
.
The rules for the format of the path to pass to the method are defined here, in the javadoc for the Class
class.
A jar is just a zip file and can be read like this..
ZipFile file = new ZipFile("/home/Desktop/myjar.jar");
Enumeration<? extends ZipEntry> entries = file.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
if (entry.getName().startsWith("splash")) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream(entry)))) {
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
}
}
The problem is Splash.txt
isn't a file, its series of bytes within in a (lightly) compressed file which has a named entry within a table of contents as specified by the Jar/Zip standard.
This measn you can use FileReader
to read the file, instead, you need to access it via the Class
resource management API, for example..
getClass().getResourceAsStream("/Splash.txt");
Or, if you're trying to read it from static
context
Splash.class.getResourceAsStream("/Splash.txt");
Don't forget, you become responsible for closing the InputStream
when you are done, for example...
try (InputStream is = getClass().getResourceAsStream("/Splash.txt")) {....