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.
FYI, I’m NOT using Axis, I’m using jax-ws, if that matters.
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;
}
}
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.
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:
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:
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.