views:

25

answers:

1

Let's say I have this structure of my Java Web Application:

TheProject
  -- [Web Pages]
  -- -- abc.txt
  -- -- index.jsp
  -- [Source Packages]
  -- -- [wservices]
  -- -- -- WS.java

WS.java is my Web Service, which is situated in a wservices package. Now from this service, I need to access the abc.txt file and write to it.

These are my urls:

http://127.0.0.1:8080/TheProject/WS  <- the webservice
http://127.0.0.1:8080/TheProject/abc.txt <- the file I want to access

To read the file, I tried with getResourceAsStream and I was successful in reading from it. But now I also want to write to this file, and I tried such a method but failed.

Is there a way I can get access to the abc.txt file from WS.java and be able to successfully read from and write to it?

A: 

You must locate the file first, and open a File object on it which you can then use as usual. Start with the URL returned by "getResource" and work your way from there.

Note: This trick makes assumptions on how the way the application server deploys your WAR-file, and will make it non-portable.

Thorbjørn Ravn Andersen
I tried that (http://stackoverflow.com/questions/2797367/write-to-a-file-stream-returned-from-getresourceasstream/2797381#2797381) but it failed with a `FileNotFoundException` exception.
Andreas Grech
Then you need closer investigation on the URL returned.
Thorbjørn Ravn Andersen