I need a file filename.txt which is inside a jar file. How can I read the contents of the txt file using code? Are there any libraries available for working with *.jar files?
public class Test {
public static void main(String[] args) {
InputStream stream = Test.class.getResourceAsStream("/test.txt");
Scanner s = new Scanner(stream);
while (s.hasNext()) {
System.out.println(s.next());
}
}
}
The jar needs to be on the classpath of the application.
This code will search for the file test.txt in the root of all jars.
If you need to specify a jar that isn't on the classpath, then the other suggestions might be more worthwhile.
If the jar is in the classpath, you can access a file in it using getClass().getClassLoader().getResourceAsStream(...). If the jar file is not in the classpath, then check out java.util.jar.JarFile.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With