开发者

Cant delete file created by the java Transformer

I am using the Transformer class in java in the following way -

1   Transformer transformerFinal = tFactory.newTransformer(new StreamSource(finalStylesheet));
2   transformerFinal.setParameter("Date", sdf.format(myDate));
3   transformerFinal.transform(new StreamSource(tempFilename), new StreamResult(new FileOutputStream(finalFilename)));

And then I want to delete this source file which was used for the transforming.

4       File fileToDelete = new File(tempFilename);                    
5       fileToDelete.delete();

It doesnt work, I mean the file doesnt get deleted.

But if at line 3 I pass a local variable of the o/p stream viz.

1   FileOutputStream fos = new FileOutputStream(finalFilename);
4   transformerFinal.transform(new StreamSource(tempFilename), new StreamResult(fo开发者_StackOverflow中文版s));
5   fos.close();

Now the delete function works and it does delete the file.

So, am I correct, when I conclude that the o/p stream is not closed implicitly during the transform process ? and hence I have to close the stream explicitly.

Can anyone please share, if there is any other reason the file may not be getting deleted?

Please assume that all the variables have correct values.

Thank You.

Update

One more thing I noticed.

I am calling this code from an another class, eg. -

public class ClassTwo {
   public void ameth(String tempFilename) {
     // the above mentioned transformation code
   }
}

1   public class ClassOne {
2       public void method1() {
3           ClassTwo ct = new ClassTwo();
4           ct.ameth("tempFilename1");
5           ct.ameth("tempFilename2");
6       }
7   }

Here, When I didn't explicitly close the stream, it did delete the tempFilename2 but not the tempFilename1.

Any idea, why it behaves so?


You're right: You can't delete a file that is still open. Due to an old bug in the Java API, the delete() can't tell you why -- it can only return a boolean result.

The reason for this behavior is that Java can't automatically clean up system resource other than heap memory. So we end up with the problem: Who can safely close the file? Maybe the transformation isn't complete, yet. Or you need to write a header+footer in the same stream.

So if you create a stream, you always have to close it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜