Tuesday 17 April 2012

Reading file in classpath

Problem: Below code shows how to read a file in classpath. The file can be in jar file or in physical file system.

Solution: We can use "java.lang.Class.getResourceAsStream(String name)" to read file
 
 
package com.lac;

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

/**
 * Reads file in the class path
 * 
 * @author lac
 */
public class ReadFile {
 public static void main(String[] args) throws IOException {

  //Read Demo.txt from class path. The file Demo.txt is in package com.lac
  InputStream is = ReadFile.class.getResourceAsStream("/com/lac/Demo.txt");
  InputStreamReader isr = new InputStreamReader(is);
  BufferedReader br = new BufferedReader(isr);
  String fileContent = "";
  StringBuilder data = new StringBuilder();

  while ((fileContent = br.readLine()) != null) {
   data = data.append(fileContent);
  }
  is.close();

  System.out.println(data);
 }

}

No comments:

Post a Comment