Monday 15 February 2010

java - Prevent file channel from closing after reading xml file -



java - Prevent file channel from closing after reading xml file -

for more detailed info regarding motivation behind goal (and efforts solve it) view previous question. decided inquire new question exclusively thought had evolved sufficiently merit doing so. summary, intend utilize jdom in combination nio in order to:

gain exclusive file lock on xml file. read file document object. make arbitrary changes (with lock still active!). write changes xml file. release file lock.

the issue getting built-in code read xml file document object closes channel (and hence releases lock), 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 = "test 2.xml"; private documentbuilderfactory dbfactory; private documentbuilder dbuilder; private document doc; public test4(){ seek (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(); } grab (ioexception | parserconfigurationexception | saxexception e) { e.printstacktrace(); } } public static void main(string[] args){ new test4(); } }

output:

true false

having looked through documentation , trawled built in java libraries, struggling find channel closed, allow lone how prevent closing. pointers great! thanks.

one clean way create filterinputstream , override close nothing:

public test() { seek { 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 } grab (ioexception | parserconfigurationexception | saxexception e) { e.printstacktrace(); } } class nonclosinginputstream extends filterinputstream { public nonclosinginputstream(inputstream it) { super(it); } @override public void close() throws ioexception { // nothing. } public void reallyclose() throws ioexception { // close. in.close(); } }

java xml concurrency io channel

No comments:

Post a Comment