Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a file from jar?

Tags:

java

jar

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?

like image 454
shift66 Avatar asked Dec 05 '25 10:12

shift66


2 Answers

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.

like image 136
pimaster Avatar answered Dec 08 '25 00:12

pimaster


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.

like image 40
andypandy Avatar answered Dec 07 '25 22:12

andypandy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!