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
rnicholusAsked:
Who is Participating?
 
rrzConnect With a Mentor Commented:
First of all, you must put your bean in a package.  
To access the file, try using  
URL fileURL = getClass().getClassLoader().getResource("index/myTextFile.txt");
FileReader fr = new FileReader(fileURL.getPath());
0
 
rnicholusAuthor Commented:
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());
0
 
rrzCommented:
>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");
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.