Prevent file channel from closing after reading xml file



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 entirely as I thought that it had evolved sufficiently to merit doing so. As a summary, I intend to use JDOM in combination with NIO in order to:



  1. Gain an exclusive file lock on an xml file.

  2. Read the file into a Document object.

  3. Make arbitrary changes (with lock still active!).

  4. Write the changes back to the xml file.

  5. Release the file lock.


The issue which I am getting however is that the code to read the xml file into a document object closes the channel (and therefore releases the lock), as seen below:



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 = "file.xml";
private FileChannel channel;
private DocumentBuilderFactory dbFactory;
private DocumentBuilder dBuilder;
private Document doc;

public Test4(){
try {
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(); //Redundant
} catch (IOException | ParserConfigurationException | SAXException e) {
e.printStackTrace();
}
}

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


Output:



true
false


Having looked through the documentation and trawled the built in Java libraries, I am really struggling to even find where the channel is closed, let alone how to prevent it closing. Any pointers would be great! Thanks.


No comments:

Post a Comment