0

I want to write an XML data inside my locked file I have a logic like this, but my file data isn't replaced by this text data and i got exception like

this:Exception in thread "main" java.nio.channels.ClosedChannelException at sun.nio.ch.FileChannelImpl.ensureOpen(FileChannelImpl.java:110) at sun.nio.ch.FileChannelImpl.write(FileChannelImpl.java:199) at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:218) at sun.nio.cs.StreamEncoder.implClose(StreamEncoder.java:316) at sun.nio.cs.StreamEncoder.close(StreamEncoder.java:149) at java.io.BufferedWriter.close(BufferedWriter.java:266) at java_io_Closeable$close.call(Unknown Source) at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:117) at locckGroovy.main(loccky.groovy:90)

. What should I change to make this?

 RandomAccessFile ini = new RandomAccessFile(file, "rwd");
        FileLock lock = ini.getChannel().tryLock();
    try{

        w=new BufferedWriter(Channels.newWriter(ini.getChannel(),"UTF-8"));
        w.write(text);

    }finally{

    ini.close();

    }
Sagitarius
  • 348
  • 1
  • 11
  • 36

1 Answers1

1

Basically, you have to close streams in the opposite order of creating/opening them.

It seems that w is being closed after ini. When trying to close w, it attempts to close the underlying stream ini, which has already been closed.

Move w.close() before ini.close(), or move ini.close() after w.close().

jurez
  • 4,436
  • 2
  • 12
  • 20
  • By the way do you know if it is enough to write w.rite(" ") for making related file empty in this code? w=new BufferedWriter(Channels.newWriter(ini.getChannel(),"UTF-8")); w.write(""); w.write(text); – Sagitarius Oct 16 '17 at 11:48
  • To make an empty file, you don't need any `write()`s. Just opening and closing it should do it as well. `write("")` actually doesn't do anything. – jurez Oct 16 '17 at 11:51
  • i mean when i write something in this file it has already have content i need to replace this data with mine – Sagitarius Oct 16 '17 at 11:52
  • In other words i need my newly updated data to be not appended but replaced – Sagitarius Oct 16 '17 at 11:56
  • You are using a `RandomAccessFile` here, I think you can use `setLength(0)` to truncate it. But do you really need a `RandomAccessFile`? If all you need is to write out a file, I suggest you use a vanilla `FileOutputStream` + `BufferedOutputStream`. It will create a new file every time. Also note you are using synchronous writes here (`"rwd"`), which might be slow. – jurez Oct 16 '17 at 12:05