SyntaxHighlighter JS

2013-02-18

Read text file from classpath

Sample Problem:
You need to read a text file, like a properties or XML file. But FileInputStream and FileReader are returning a FileNotFoundException.

Solution:
FileInputStream and FileReader need the absolute physical file path to read a file. Hard coding the absolute file path makes the program not portable to different machines. It is better practice to read the text file on the Java classpath.
  1. Read the text file with ClassLoader.getResource
    Use the Java class loader to read the file. For example, let's assume you need to read the text file application.properties from the class TextTest.java. The config directory is where application.properties is located.

    To read the file, use the code below to get an InputStream from the file.

    URL fileUrl = TextTest.class.getClassLoader().getResource("application.properties");
    System.out.println("Absolute File Path " + fileUrl.getPath());
    InputStream in = fileUrl.openStream();

  2. Set the classpath to the directory with the text file
    Include the path to the text file directory in the java classpath and run the program

    java -cp .:config TextTest

No comments:

Post a Comment