W3docs

How to read text file from classpath in Java?

To read a text file from the classpath in Java, you can use the getResourceAsStream method of the ClassLoader class to get an InputStream for the file, and then use a BufferedReader to read the contents of the file.

To read a text file from the classpath in Java, you can use the getResourceAsStream method of the ClassLoader class to get an InputStream for the file, and then use a BufferedReader to read the contents of the file.

Here's an example of how you can read a text file from the classpath in Java:


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ClasspathReader {
    public static void main(String[] args) {
        InputStream is = ClasspathReader.class.getClassLoader().getResourceAsStream("/file.txt");
        if (is == null) {
            System.out.println("File not found on classpath.");
            return;
        }

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this example, the getResourceAsStream method is used to get an InputStream for the file /file.txt from the classpath. The leading slash ensures the path is resolved from the absolute classpath root. The InputStream is then wrapped in an InputStreamReader, which is used to create a BufferedReader. The BufferedReader is then used to read the lines of the file one by one and print them to the console. The try-with-resources statement automatically handles closing the reader.

Keep in mind that the getResourceAsStream method will search for the file in the classpath. The classpath is the set of locations that the Java runtime searches for classes and other resources. By default, it includes the current working directory. You can specify additional locations on the classpath by using the -cp or -classpath command-line option when starting the Java application.