Friday, December 15, 2006

Reading a File using Java


When we want to read a file in Java we usually use the following piece of code for doing it.

try
{
BufferedReader in = new BufferedReader(new FileReader("c:/test/test.xml"));
String str;
while ((str = in.readLine()) != null)
{
System.out.println(str);
}
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}

But this will work only if the absolute path of file is given. If you want to read a file which is in the class pathor inside a jar file in classpath by just giving the file name, then the above said code piece will give a FileNotFoundException.To solve that issue and make the program read a file from classpath or from a jar file in classpath use thefollowing piece of code.

try
{
InputStream is =
Thread.currentThread().getContextClassLoader().getResourceAsStream ("test.xml");
InputStreamReader isr = new InputStreamReader(is);
BufferedReader in = new BufferedReader(isr);
String str;
while ((str = in.readLine()) != null)
{
System.out.println(str);
}
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}








1 comment:

Ramita said...

Extremely helpful :)