我想在文件中附加一行文字 - 但是,我想在文件中获取字符串的位置,以便我可以使用RandomAccessFile
和{{1}直接访问字符串(或类似的)
问题是很多文件i / o操作都是异步的,并且写操作可以在很短的时间间隔内发生 - 这表明异步写入,因为其他一切都是低效的。如何确保正确计算filepointer?我是Java的新手,并且还不了解File I / O的不同方法的细节,所以请原谅我的问题,如果使用BufferedWriter正是我正在寻找的,但是你如何获得当前的长度呢? / p>
编辑:阅读整个文件不是一个选择。文件很大,正如我所说,写操作经常发生,在高峰时间每秒发生几百次。
答案 0 :(得分:0)
请参阅 FileChannel 类:http://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html
链接中的相关摘录:
The file itself contains a variable-length sequence of bytes that can be read and written and whose current size can be queried. The size of the file increases when bytes are written beyond its current size;
...
File channels are safe for use by multiple concurrent threads. The close method may be invoked at any time, as specified by the Channel interface. Only one operation that involves the channel's position or can change its file's size may be in progress at any given time; attempts to initiate a second such operation while the first is still in progress will block until the first operation completes. Other operations, in particular those that take an explicit position, may proceed concurrently; whether they in fact do so is dependent upon the underlying implementation and is therefore unspecified.