Prevent file channel from closing after reading xml file

可紊 提交于 2019-11-29 16:24:57

One clean way to do this is to create a FilterInputStream and override the close to do nothing:

public Test() {
    try {
        channel = new RandomAccessFile(new File(path), "rw").getChannel();
        dbFactory = DocumentBuilderFactory.newInstance();
        dBuilder = dbFactory.newDocumentBuilder();

        System.out.println(channel.isOpen());
        NonClosingInputStream ncis = new NonClosingInputStream(Channels.newInputStream(channel));
        doc = dBuilder.parse(ncis);
        System.out.println(channel.isOpen());
        // Closes here.
        ncis.reallyClose();
        channel.close(); //Redundant
    } catch (IOException | ParserConfigurationException | SAXException e) {
        e.printStackTrace();
    }
}

class NonClosingInputStream extends FilterInputStream {

    public NonClosingInputStream(InputStream it) {
        super(it);
    }

    @Override
    public void close() throws IOException {
        // Do nothing.
    }

    public void reallyClose() throws IOException {
        // Actually close.
        in.close();
    }
}

Did you try the try-with-ressource statment? Even though, this is not the main purpose of this feature, maybe that does what you are looking for (in form of auto closing the ressources (your channel), but only when you leave the corresponding try-block)

try (final Channel channel = new RandomAccessFile(new File(path), "rw").getChannel()) {
  // your stuff here
} catch (IOException ex) {
  ex.printStackTrace();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!