Search code examples
javaxmlfileioxstream

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?


Solution

  • 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.