If you happen to use StreamSource for whatever reason, you might have encountered FileSystemExceptions if you used it like that:
File xmlFile = new File("asdf.txt");
final StreamSource source = new StreamSource(xmlFile.toFile());
// other operations
If you try to move or delete this file later on you will get: java.nio.file.FileSystemException the process cannot access the file because it is being used by another process. The reason for this is simple. By passing File directly into StreamSource you lose control of how/when to close the file handle. Using a FileInputStream will solve this problem:
final FileInputStream inputStream = new FileInputStream(xmlFile.toFile());
final StreamSource source = new StreamSource(inputStream);
// do anything you want
inputStream.close();
We should never forget to close a stream after using it. To be certain that a stream is closed, even if something goes wrong, we have to do proper exeption handling: FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(xmlFile.toFile());
final StreamSource source = new StreamSource(inputStream);
// other code here
} catch (final Exception e) {
// handle your exceptions
} finally {
if(inputStream!=null){
try {
inputStream.close();
} catch (final IOException e) {
// report
}
}
This way the sream gets closed, even if an exception was thrown by another part of the code inside the try block.
No comments:
Post a Comment