[英]Accessing a file (for writing) from a JBoss Web Service
Let's say I have this structure of my Java Web Application: 假设我具有Java Web应用程序的以下结构:
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. WS.java
是我的Web服务,位于wservices
包中。 Now from this service, I need to access the abc.txt
file and write to it. 现在,通过此服务,我需要访问
abc.txt
文件并对其进行写入。
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. 要读取文件,我尝试使用
getResourceAsStream
并成功读取了该文件。 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? 有没有一种方法可以使我从
WS.java
访问abc.txt
文件,并且能够成功读取和写入该文件?
You must locate the file first, and open a File object on it which you can then use as usual. 您必须首先找到该文件,然后在其上打开一个File对象,然后可以照常使用它。 Start with the URL returned by "getResource" and work your way from there.
从“ getResource”返回的URL开始,然后从那里开始。
Note: This trick makes assumptions on how the way the application server deploys your WAR-file, and will make it non-portable. 注意:此技巧将对应用程序服务器部署WAR文件的方式做出假设,并将使其不可移植。
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)
您可以通过从以下路径访问文件来访问它:(我假设您的Web服务打包在WAR文件中)
@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. 但是写一个总的来说是个坏主意-JBOSS会将您的应用程序解压缩到一些tmp文件夹中。 So every time your application restarts you'll receive the new foo.txt
因此,每次您的应用程序重新启动时,您都会收到新的foo.txt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.