wood burning stoves 2.0*
The moose likes Servlets and the fly likes reading a file located on the server Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "reading a file located on the server" Watch "reading a file located on the server" New topic
Author

reading a file located on the server

Sara Tracy
Ranch Hand

Joined: Jan 06, 2006
Posts: 45
hi,

programX calls my servlet that has been deployed on the server (Windows) (servlet8.war).

In my servlet, I'm trying to read a file that is present on the same server, and display the contents as output. In my program, I have hardcoded the path of the file (on the server), and it is actually working fine.

But I'm sure this is not the right way to go about, as the directory can change on the server (example: C: or F: or D . Is there a better way of coding for accessing a file on the server?


**********************************************************
String Name = request.getHeader(headerName);
String fileName = " ";
String filePath = "c:\\TestFiles\\";

fileName = filePath + Name

//read contents of the file...
************************************************************

Thanks,
Sara
Mike Noel
Ranch Hand

Joined: Dec 15, 2005
Posts: 108
The ClassLoader.getResourceAsStream(String name) method will probably help you out here. It will find the specified file (by name) in your classpath and return an InputStream object to it. With this method you can put your file in any of the directories on your classpath (maybe even in your war's top-level dir) and the class loader will find it.

_M_


Mike Noel
Sara Tracy
Ranch Hand

Joined: Jan 06, 2006
Posts: 45
Mike,

Thanks for the help. However, I guess I didn't word my question properly. I'll get back to the forums a little later.

-Sara.
Vishnu Prakash
Ranch Hand

Joined: Nov 15, 2004
Posts: 1026
ServletContext.getRealPath(String path) will help you. But this method will return "null" when your web application is deployed as a war file. So if you want your web application to be portable then you got to use the following methods of ServletContext

getResource(String path) (or)
getResourceAsStream(String path).

I assume the resource you intend to access is NOT part of the WEB-INF/lib jar file(or) outside the web-application. If its the case then you got to use the following methods of java.lang.ClassLoader class.

getResource(String path) (or)
getResourceAsStream(String path).


Servlet Spec 2.4/ Jsp Spec 2.0/ JSTL Spec 1.1 - JSTL Tag Documentation
Sara Tracy
Ranch Hand

Joined: Jan 06, 2006
Posts: 45
thanks for the reply, Vishnu.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: reading a file located on the server