Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - XStream closing connection to File

I load my XML like this:

File f = new File("Results\\" + filename);
xstream.fromXML(f);
Boolean delete = f.delete();

After using XStream successfully I want to delete my file. I am not able to do so because XStream is still open and so my file can't be deleted. How can I close my connection and delete my file?

like image 302
E. van der Spoel Avatar asked Feb 06 '26 19:02

E. van der Spoel


1 Answers

File file = new File(...);
try (InputStream inputStream = new FileInputStream(file)) {
    ...
    xstream.fromXML(file);
    ...
} catch (Exception e) {
    log.debug(e);
} finally {
    inputStream.close();
}

If an exception was thrown, the inpuStream would be closed correctly. And if everthing works fine - the InputStream would be closed corretly within the finally block.

like image 158
Dirk Rother Avatar answered Feb 09 '26 11:02

Dirk Rother