How to read a file from a Jar

By | September 29, 2021
How to read a file from a Jar

Introduction

If you are trying to read a text file from Jar using the File class, stop right there. The right method is to get the resource as a stream using the InputStream class. We will also see how you can get the file path from the command line instead of hardcoding it.

How to read a text file from Java Jar

We can read text from any file like .txt, .csv etc using the InputStream class. Note that you should either add a try/catch or throws clause to handle IOException.

InputStream inputstream = getClass().getResourceAsStream("file.txt");
    InputStreamReader ipstreader = new InputStreamReader(inputstream);
    BufferedReader breader = new BufferedReader(ipstreader);
    String line;
    while ((line = breader.readLine()) != null)
    {
      System.out.println(line);
    }
    breader.close();
    ipstreader.close();
    inputstream.close();

If your file is not in the current folder (as that of the Java program), you should specify the complete path, like:

"C:\\Users\\Desktop\\myfile.txt"

JarFile is a class in java.util.jar package, which identifies a jar file from its name and JarEntry gets the path. We can use the Java command-line arguments to get the filename and location using these classes. If you are using Eclipse, you can type the arguments by opening the Run dialog.

   JarFile jarFile = new JarFile(args[0]);
         JarEntry file = jarFile.getJarEntry(args[1]);
         InputStream inputstream = jarFile.getInputStream(file);

Don’t forget to close the jarFile using jarFile.close() method in the end.

Vamware

Conclusion

Note that we have individually closed the InputStream, BufferedReader, and other classes. You cannot close all the resources using a single close statement. Hence make sure you put the close() statements for each resource. We can also get the resource using ClassLoader using the getClassLoader() method. Make sure you have all the imports in place. For convenience, you can use java.util.jar.* and java.io.*.

People are also reading: 

Vamware

Leave a Reply

Your email address will not be published. Required fields are marked *