2

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?

Community
  • 1
  • 1
Andreas Grech
  • 105,982
  • 98
  • 297
  • 360

2 Answers2

0

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
  • 73,784
  • 33
  • 194
  • 347
0

well, access for reading is possible. You can get access to it by accessing file from the following path: (I'm assuming that your web service is packed inside of the WAR file)

@Resource
private WebServiceContext context;
......
// receive the realpath to foo.txt inside of web-archive deployment
((ServletContext )context.getMessageContext().get(MessageContext.SERVLET_CONTEXT)).getRealPath("foo.txt")

But writting there is a bad idea in general - JBOSS will unpack your application to some tmp folder. So every time your application restarts you'll receive the new foo.txt

Ilya Dyoshin
  • 4,459
  • 1
  • 19
  • 18