java - 读取xml文件后防止文件 channel 关闭

标签 java xml concurrency io channel

有关此目标背后的动机(以及我为解决它所做的努力)的更多详细信息,请查看我的 previous question .我决定完全将此作为一个新问题来提出,因为我认为它已经发展到足以值得这样做的地步。总而言之,我打算将 JDOM 与 NIO 结合使用,以便:

  1. 获得 xml 文件的独占文件锁。
  2. 将文件读入 Document 对象。
  3. 进行任意更改(锁定仍处于 Activity 状态!)。
  4. 将更改写回 xml 文件。
  5. 释放文件锁。

然而,我遇到的问题是将 xml 文件读入文档对象的内置代码关闭了 channel (因此释放了锁),如下所示:

import java.io.*;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import javax.xml.parsers.*;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class Test4{ 
    String path = "Test 2.xml";
    private DocumentBuilderFactory dbFactory;
    private DocumentBuilder dBuilder;
    private Document doc;

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

            System.out.println(channel.isOpen());
            doc = dBuilder.parse(Channels.newInputStream(channel));
            System.out.println(channel.isOpen());

            channel.close();
        } catch (IOException | ParserConfigurationException | SAXException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args){
        new Test4();
    }
}

输出:

true
false

查看了文档并搜索了内置的 Java 库后,我真的很难找到 channel 关闭的位置,更不用说如何防止它关闭了。任何指针都会很棒!谢谢。

最佳答案

一种干净的方法是创建一个 FilterInputStream 并覆盖 close 以不执行任何操作:

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();
    }
}

关于java - 读取xml文件后防止文件 channel 关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26605671/

相关文章:

java - 由于 ClassNotFoundException,Quartz 失火

java - 如何在Hadoop中使用CombineFileInputFormat?

java - 生成的源中的 Netbeans 注释

c++ - 删除 XML 文件 C++ 中的子节点

xml - 匹配特定父节点XSLT的特定子属性

java - 在线程池执行器中顺序处理文件

Java同步原语

c# - Java 中的拖放应用程序,如 .Net 中的 IDesignerHost

java - 访问子节点的长度返回原始计数的两倍

concurrency - 招聘经理希望开发人员理解哪些并发编程概念?