简体   繁体   中英

Accessing a file (for writing) from a 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 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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM