Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

FileInputStream in Servlets

 
vivek parepalli
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I am trying to access a txt file from the service method of Servlet code. I am getting a Null Pointer Exception at this line

FileInputStream fis= new FileInputStream(source);

I have placed the source file in all possible locations. But still I am getting the same problem.

What would be the right location to place the source file. My servlet hierarchy looks like this:

+Servlet Folder
+WEB-INF
+CLASSES
-servlet.java&class
+LIB
-web.xml

Hope someone helps me out.
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13056
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
FileInputStream fis= new FileInputStream(source);

I have placed the source file in all possible locations. But still I am getting the same problem.

The problem is not where the file is but the way you are referring to it. If you are not giving a complete path but using the "filename.typ" only, it will never work reliably. The reason being that with just the filename, the JVM assumes the "current" directory - something you have utterly no control over in the servlet environment.
Either code a complete path or use something like the ServletContext getRealPath method.
Bill
 
Adeel Ansari
Ranch Hand
Posts: 2874
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moreover, doing file I/O or database operations in servlet is not a good practice.

Thanks.
 
ramprasad madathil
Ranch Hand
Posts: 489
Eclipse IDE Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you have to read from a file, then you have to

Use the getResourceAsStream(String path) method of the ServletContext object. The path must begin with a "/" and is interpreted as relative to the current context root. For eaxmple if you have a file called 'test.txt' in the context root folder of your web-app,



cheers,
ram.
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13056
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moreover, doing file I/O or database operations in servlet is not a good practice.

Perhaps the intended statement was related to doing file I/O or database operations inside the servlet class code - for instance the service method. You will find it much easier to test and debug if such operations are in "helper" classes.
Bill

[ November 25, 2005: Message edited by: William Brogden ]
[ November 25, 2005: Message edited by: William Brogden ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic