Prevent file channel from closing after reading xml file

前端 未结 2 1319
春和景丽
春和景丽 2020-12-22 05:08

For more detailed information regarding the motivation behind this goal (and my efforts to solve it) view my previous question. I decided to ask this as a new question entir

相关标签:
2条回答
  • 2020-12-22 05:19

    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();
        }
    }
    
    0 讨论(0)
  • 2020-12-22 05:23

    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();
    }
    
    0 讨论(0)
提交回复
热议问题