• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 175
  • Last Modified:

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
0
rnicholus
Asked:
rnicholus
  • 2
1 Solution
 
rrzCommented:
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

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now