Failed to delete file created by java Transformer


I am using the Transformer class in java as follows -

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 that was used for conversion.

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

It does not work, I mean that the file is not deleted.
But if at line 3 , I pass the local stream variable o / p, namely.

 1 FileOutputStream fos = new FileOutputStream(finalFilename); 4 transformerFinal.transform(new StreamSource(tempFilename), new StreamResult(fos)); 5 fos.close(); 

Now the delete function works and it deletes the file.
So, is it right when I conclude that the o / p stream does not close implicitly during the transform process? and therefore I have to close the stream explicitly.
Can anyone share if there is any other reason why the file cannot be deleted?

Suppose all variables have the correct values.

Thanks.

Update

Another thing I noticed.
I am calling this code from another class, for example. -

 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 did not explicitly close the stream, it removed tempFilename2 , but not tempFilename1 .
Any idea why she is behaving this way?

+4
source share
1 answer

You are right: you cannot delete a file that is still open. Due to an old error in the Java API, delete() cannot tell you why - it can return a boolean result.

The reason for this behavior is that Java cannot automatically flush a system resource other than heap memory. Therefore, we have a problem: who can safely close the file? Maybe the transformation is not completed yet. Or you need to write a header + footer in the same thread.

So, if you create a thread, you should always close it.

+5
source

Source: https://habr.com/ru/post/1342611/


All Articles