Tuesday, December 21, 2010

Java Resource Locator. Best practice to open a File

Here I would like to discuss about the Loading of a Resource in a Java Application.For example lets take the Java sample eclipse project Test. Here we have different Package as 1. org.work.corejava, 2. org.work.corejava.file.csvreader also 3.org.work.corejava.xml.parser,
In the above Example if i want to read the InputData.txt file need to be read in the ResouceLocator.java,
Normally we do as follows.

public class ResourceLocator {
 public static void main(String[] args) {
  File fileIn = new File("InputData.TXT");
  FileReader fileReader = null;
  BufferedReader reader = null;
  try {
   fileReader = new FileReader(fileIn);
   reader = new BufferedReader(fileReader);
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  }finally{
   try{
    reader.close();
   }catch(Exception e){}
  }
 }
}
But It will throw the following Exception 

java.io.FileNotFoundException: InputData.TXT (The system cannot find the file specified)
 at java.io.FileInputStream.open(Native Method)
 at java.io.FileInputStream.(Unknown Source)
 at java.io.FileReader.(Unknown Source)
 at org.work.corejava.ResourceLocator.main(ResourceLocator.java:25)
The reason behind this Exception is the Application is searching the InputData.TXT in the base class path. Basically inside the SRC Folder. But the File is in the src/org/work/corejava folder. To avoid the above exception we can simply copy the InputData.TXT to the src folder and the issue resolved. otherwise provide the Entire path as follows.
File fileIn = new File("D:\\Development\\workspace\\Test\\org\\work\\corejava\\InputData.TXT");

The best way to do this is by using the Class.getResource Method as follows.
URL url=ResourceLocator.class.getResource("InputData.TXT");
fileReader = new FileReader(url.getFile());
Here we will keep the File and the Java FIle in the same package.
The complete program is as follows.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;

/**
 * To find the Resource by using the Java Resource Locator.
 * @author askeralim
 *
 */
public class ResourceLocator {
 public static void main(String[] args) throws IOException {
  FileReader fileReader = null;
  BufferedReader reader = null;
  try {
   URL url=ResourceLocator.class.getResource("InputData.TXT");
   fileReader = new FileReader(url.getFile());
   reader = new BufferedReader(fileReader);
   String data =reader.readLine();
   System.out.println(data);
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  }finally{
   try{
    reader.close();
   }catch(Exception e){}
  }
 }
}

No comments: