Read a file inside of JAR in JAVA

March 19, 2016 | 447 views | Comments

Read a text file inside a jar file using the method getResourceAsStream of the Class Loader. Null will be returned if the file was not found, otherwise, it will return an input stream for reading the resource

 

try {
    /*
     * Put the file in the source directory
     * and set it up here.
     */
    InputStream is = Main.class.getResourceAsStream("/FILE-NAME");
    
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    try {
        String line;
        /*
         * Iterate through each line.
         */
        while( (line =  br.readLine()) != null) {
            /*
             * Do whatever is needed on the value of the line.
             */
            System.out.println(line);
        }
        br.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
} catch (Exception e1) {
    e1.printStackTrace();
}

Related Tutorials


Must Read