File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

reading a file located on the server

 
Sara Tracy
Ranch Hand
Posts: 45
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 108
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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_
 
Sara Tracy
Ranch Hand
Posts: 45
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1026
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
Sara Tracy
Ranch Hand
Posts: 45
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks for the reply, Vishnu.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic