SyntaxHighlighter JS


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.

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 from the class The config directory is where is located.

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

    URL fileUrl = TextTest.class.getClassLoader().getResource("");
    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