Tomcat 6:如何在Web方法调用结束后删除临时文件? [英] Tomcat 6: how to delete temporary files after a web method call has ended?
问题描述
我有一个临时文件,其中的数据是通过MTOM二进制附件作为SOAP响应的一部分返回的.我想在方法调用结束"(即完成传输)后立即对其进行垃圾处理.对我来说最好的方法是什么?我能弄清楚如何执行此操作的最佳方法是在会话被销毁时将其删除,但是我不确定是否有更直接"的方法来执行此操作.
I have a temporary file with data that's returned as part of a SOAP response via a MTOM binary attachment. I would like to trash it as soon as the method call "ends" (i.e., finishes transferring). What's the best way for me to do this? The best way I can figure out how to do this is to delete them when the session is destroyed, but I'm not sure if there's a more 'immediate' way to do this.
仅供参考,如果需要的话,我不使用Axis,而是使用jax-ws.
FYI, I'm NOT using Axis, I'm using jax-ws, if that matters.
更新:我不确定回答者是否真的了解这个问题.我知道如何在Java中删除文件.我的问题是这样:
UPDATE: I'm not sure the answerers are really understanding the issue. I know how to delete a file in java. My problem is this:
@javax.jws.WebService
public class MyWebService {
...
@javax.jws.WebMethod
public MyFileResult getSomeObject() {
File mytempfile = new File("tempfile.txt");
MyFileResult result = new MyFileResult();
result.setFile(mytempfile); // sets mytempfile as MTOM attachment
// mytempfile.delete() iS WRONG
// can't delete mytempfile because it hasn't been returned to the web service client
// yet. So how do I remove it?
return result;
}
}
推荐答案
我遇到了同样的问题.问题是JAX-WS堆栈管理文件.无法在代码中确定何时对文件执行JAX-WS,因此您不知道何时删除它.
I ran into this same problem. The issue is that the JAX-WS stack manages the file. It is not possible to determine in your code when JAX-WS is done with the file so you do not know when to delete it.
就我而言,我在对象模型而不是文件上使用DataHandler. MyFileResult将具有以下字段而不是文件字段:
In my case, I am using a DataHandler on my object model rather than a file. MyFileResult would have the following field instead of a file field:
private DataHandler handler;
我的解决方案是创建FileDataSource的自定义版本.我没有返回FileInputStream来读取文件的内容,而是返回了FileInputStream的以下扩展名:
My solution was to create a customized version of FileDataSource. Instead of returning a FileInputStream to read the contents of the file, I return the following extension of FileInputStream:
private class TemporaryFileInputStream extends FileInputStream {
public TemporaryFileInputStream(File file) throws FileNotFoundException {
super(file);
}
@Override
public void close() throws IOException {
super.close();
file.delete();
}
}
基本上,数据源只允许读取一次.流关闭后,文件将被删除.由于JAX-WS堆栈仅读取一次文件,因此可以正常工作.
Essentially the datasource allows reading only once. After the stream is closed, the file is deleted. Since the JAX-WS stack only reads the file once, it works.
该解决方案有些破绽,但在这种情况下似乎是最佳选择.
The solution is a bit of a hack but seems to be the best option in this case.
这篇关于Tomcat 6:如何在Web方法调用结束后删除临时文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!