File access (for writing) from JBoss web service

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 in a package wservices

. Now from this service I need to access the file abc.txt

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 able to read it. But now I also want to write to this file and I tried this kind of method but couldn't.

Is there a way to access the abc.txt

file from WS.java

and be able to read and write to it successfully?

+2


a source to share


2 answers


You must first find the file 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 up from there.



Note. This trick makes assumptions about how the application server deploys your WAR file and makes it non-portable.

0


a source


Well, read access is possible. You can access it by accessing the file in the following path: (I am assuming your web service is packaged inside a 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 writing is a generally bad idea - JBOSS will unpack your application into some kind of tmp folder. So every time your app reloads you get a new foo.txt file

0


a source







All Articles