Link to home
Start Free TrialLog in
Avatar of rnicholus
rnicholus

asked on

Accessing text file from a bean.

Hello,

I'm trying to access a text file from a bean.
Here's my directory structure:
C:/tomcat/webapps/  ----> I have all the jsp pages here.
C:/tomcat/webapps/WEB-INF/classes ----> I have a java file where I'm trying to acces access the text file in C:/tomcat/webapps/WEB-INF/classes/index/myTextFile.txt

This is what I do in the java code:
String fileName = "index/myTextFile.txt";
FileReader fileReader = new FileReader(fileName);
But it doesn't find myTextFile.txt.
When I put the whole path into fileName: C:/tomcat/webapps/WEB-INF/classes/index/myTextFile.txt, it works. But I actually don't want this since I should put the code somewhere else.

I've also tried to do this and this doesn't work either:
String fileName = "index/myTextFile.txt";
File myFile = new File(fileName);
String absolutePath = myfile.getAbsolutePath();
FileReader fileReader = new FileReader(absolutePath);

Could someone please advice?

Thanks
ASKER CERTIFIED SOLUTION
Avatar of rrz
rrz
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of rnicholus
rnicholus

ASKER

Thanks! It works.

I think the getClass() method is not a static method so I did this:
URL fileURL = Class.forName("beans.myClassName").getClassLoader().getResource("index/myTextFile.txt");
FileReader fr = new FileReader(fileURL.getPath());
>I think the getClass() method is not a static method  
You are right. But  
>URL fileURL = getClass().getClassLoader().getResource("index/myTextFile.txt");  
 is the same as  
URL fileURL = this.getClass().getClassLoader().getResource("index/myTextFile.txt");