0

I have a GWT application and I load a .json file on the server side like this:

InputStream source = new FileInputStream(testFile.json); 

This works perfectly when I start the application directly in eclipse. However, when I deploy the app on tomcat, it does not work. It seems like, that the application is looking for that file in the bin folder of tomcat (???). However, the correct path would be tomcat/webapps/myProject/testFile.json.

Does anyone know how to get the correct path (without harcoding it)?

mkn
  • 12,024
  • 17
  • 49
  • 62

1 Answers1

1

The FileInputStream locates files depending on the current working directory, which in turn depends on the way how you started the application, which in turn is thus not controllable from inside your application. In case of web applications, you need ServletContext#getResourceAsStream() instead of FileInputStream to obtain web application's own resources. It takes a path which is relative to the web content folder.

InputStream input = getServletContext().getResourceAsStream("/testfile.json");
// ...

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • do you mean with 'servletContext' the file name of the class calling the getResourceAsStream(..) function? – mkn Sep 11 '11 at 16:18
  • No, it's the `ServletContext` class. See also the `ServletContext#getResourceAsStream()` link in my answer. In a class which extends from `Servlet`, it's available by the inherited `getServletContext()` method. – BalusC Sep 11 '11 at 16:20
  • So, if your servlet class extends from [`RemoteServiceServlet`](http://google-web-toolkit.googlecode.com/svn/javadoc/1.5/com/google/gwt/user/server/rpc/RemoteServiceServlet.html) then you should be able to get it by `getServletContext()`. – BalusC Sep 11 '11 at 16:27
  • what if I need the path in a class which does not inherit from RemoteServiceServlet? I don't want to pass the ServletContext through all method calls. Just instantiate a new RemoteServiceServlet in another class seems to be pretty wrong :s – mkn Sep 12 '11 at 19:02
  • I don't do GWT, but Google teaches me that Spring is very helpful in providing this information by an interface. As a completely different alternative, you can also just drop that file in the classpath (surely if it is never requested without intervention of a GWT servlet) so that you can just get it from context's class loader. – BalusC Sep 12 '11 at 19:05
  • hmm... well I tried it this way: Class.class.getResourceAsStream("test.json"); but this works also only fine when I run it in eclipse... – mkn Sep 13 '11 at 09:12
  • In web applications, you must use the thread's context class loader. See also the "See also" link in my answer. – BalusC Sep 13 '11 at 12:16