wood burning stoves 2.0*
The moose likes Servlets and the fly likes Reading .txt from a helper class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Reading .txt from a helper class" Watch "Reading .txt from a helper class" New topic
Author

Reading .txt from a helper class

Dave Thomas
Ranch Hand

Joined: Nov 05, 2001
Posts: 30
Hi there,
I have a helper class in a directory classes\utilities and I would like it to be able to read a text file - (to access the driver name, connectionURL, etc for a database). Problem is, I'm getting a FileNotFoundException. I've placed the file under the utitlities directory, classes, and public but still no access. I'm refering to the file as simply "fileName" which I suspect may be the problem ... but then what do I know? I'm the one with the problem here. Any ideas would be greatly appreciated.
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12769
    
    5
You can never use a plain file name to open a file in a servlet because you can never be sure what the "current" directory is. I like to use a servlet init-param to set the absolute path to a "working directory" that can then be used to locate files, but there are other way of doing this.
Bill
Dave Thomas
Ranch Hand

Joined: Nov 05, 2001
Posts: 30
So when I initialise the directories with my init - param, I just append those directories to the filename I need when accessing it? Is the working directory you specify just on the drive outside the web application or can it be in the web application directory structure itself?
[ March 27, 2002: Message edited by: Caveman Thomas ]
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12769
    
    5
Since you can use an absolute path, the working directory can be anywhere. Then you just use the File constructor that takes path and filename separately and not bother about trying to construct a complete path/filename.
File f = new File( workdir, myfile );
Now you can use f.exists(), f.length(), f.canRead() and other cool File methods before you even try to open it.
Bill
Sean Li
Ranch Hand

Joined: Feb 27, 2002
Posts: 154
but how to return work directory? that's a problem.
now, i'm using struts, in the action class, how can i get the work directory from a httpservletrequest?
thank you and wait for your earlier reply.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Reading .txt from a helper class