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.
Here's an example of how you can read a text file from the classpath in Java:
InputStream is = getClass().getClassLoader().getResourceAsStream("file.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
In this example, the getResourceAsStream
method is used to get an InputStream
for the file "file.txt" from the classpath. 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.
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, the classpath includes the current directory and the JAVA_HOME/lib
directory. You can specify additional locations on the classpath by using the -cp
or -classpath
command-line option when starting the Java application.