简体   繁体   English

如何在锁定文件中写入数据?

[英]How to write data in locked file?

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 我想在锁定的文件中写入XML数据,我有这样的逻辑,但是我的文件数据没有被此文本数据替换,并且出现了异常

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) this:线程“主”中的异常,位于sun.nio.ch.FileChannelImpl.ensureOpen(FileChannelImpl.java:110)处的sun.nio.ch.FileChannelImpl.ensureOpen(FileChannelImpl.java:110)处,位于以下位置: sun.nio.cs.StreamEncoder.close(StreamEncoder.java:149)上的sun.nio.cs.StreamEncoder.implClose(StreamEncoder.java:316)上的sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:218)在java.io.BufferedWriter.close(BufferedWriter.java:266)在org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)的java_io_Closeable $ close.call(未知源) .groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)位于org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:117)位于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();

    }

Basically, you have to close streams in the opposite order of creating/opening them. 基本上,您必须按照创建/打开它们的相反顺序关闭流。

It seems that w is being closed after ini . 看来ini之后w正在关闭。 When trying to close w , it attempts to close the underlying stream ini , which has already been closed. 当尝试关闭w ,它将尝试关闭已经关闭的基础流ini

Move w.close() before ini.close() , or move ini.close() after w.close() . 移动w.close()之前ini.close()或移动ini.close()w.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM