Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Devops
  3. Question
Devops

reading a resource file from within jar

Asked by Danilo Guidi Jul 5, 2021 6.2K views 3 answers
Share

About this question

 I would like to read a resource from within my jar like so:

File file;
file = new File(getClass().getResource("/file.txt").toURI());
BufferredReader reader = new BufferedReader(new FileReader(file));
//Read the file

and it works fine when running it in Eclipse, but if I export it to a jar the run it there is an IllegalArgumentException:

Exception in thread "Thread-2"
java.lang.IllegalArgumentException: URI is not hierarchical

and I really don't know why but with some testing I found if I change

file = new File(getClass().getResource("/file.txt").toURI());

to

file = new File(getClass().getResource("/folder/file.txt").toURI());

then it works the opposite (it works in jar but not eclipse).

I'm using Eclipse and the folder with my file is in a class folder.

Your answer

3 Answers

Ranjana Admin JanBask Expert Latest answer

Answered on Mar 17, 2025

If you're trying to read a resource file inside a JAR, here’s how you can do it properly in Java.


1. Why Can’t You Read Files Normally Inside a JAR?

  • A JAR file is a compressed archive, so you can’t use File class to access internal resources.
  • Instead, you need to use ClassLoader or getResourceAsStream().

2. How to Read a Resource File in a JAR?

 Method 1: Using getResourceAsStream() (Recommended)

import java.io.*;
public class ReadResource {
    public static void main(String[] args) {
        try (InputStream inputStream = ReadResource.class.getResourceAsStream("/config.properties")) {
            if (inputStream == null) {
                System.out.println("File not found!");
                return;
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 getResourceAsStream("/filename") works inside a JAR.

  Always check for null in case the file is missing.

  Use BufferedReader for efficient reading.

 Method 2: Using ClassLoader

  InputStream inputStream = ReadResource.class.getClassLoader().getResourceAsStream("config.properties");

 Works similarly but does not require a leading /.

3. Where Should You Place Resource Files?

  • Put them in src/main/resources/ (for Maven projects).
  • Make sure they are included in the JAR under resources/.

4. Final Thoughts

  •  Don’t use File, use getResourceAsStream() instead.
  •   Check for null to avoid crashes.
  •   Keep resource files in resources/ directory.


Was this helpful?

Ranjana Admin JanBask Expert

Answered on May 14, 2024

To read a resource file from within a JAR file in Java, you can use the ClassLoader.getResourceAsStream() method or Class.getResourceAsStream() method. These methods allow you to obtain an InputStream representing the contents of the resource file.


Here's an example of how to read a resource file from within a JAR:

import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
public class ReadResourceFromJar {
    public static void main(String[] args) {
        // Get the InputStream for the resource file
        InputStream inputStream = ReadResourceFromJar.class.getResourceAsStream("/path/to/resource/file.txt");
        if (inputStream != null) {
            try (Scanner scanner = new Scanner(inputStream)) {
                // Read the contents of the resource file
                while (scanner.hasNextLine()) {
                    String line = scanner.nextLine();
                    System.out.println(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("Resource not found!");
        }
    }
}

In this example:

Replace "/path/to/resource/file.txt" with the actual path to your resource file inside the JAR. The path should be relative to the root of the JAR file, and it should start with a /.

The getResourceAsStream() method returns an InputStream for the resource file. If the resource is not found, it returns null.

We use a Scanner to read the contents of the resource file line by line.

Make sure to handle exceptions that may occur during the reading process, such as IOException.

When you run this code, it will read the contents of the resource file from within the JAR and print them to the console.




Was this helpful?

More Devops discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest DevOps Blogs

Guides, tips and career advice on DevOps from JanBask experts.