2014-01-20 39 views
0

我想將一行文本附加到文件中 - 但是,我想要獲取文件中字符串的位置,以便可以直接使用字符串一個RandomAccessFilefile.seek()(或類似)安全地獲取文件末尾的文件指針

的問題是,很多文件的I/O操作的非同步,並且寫操作可以很短的時間間隔內發生的 - 這表明一個非同步寫,因爲一切是低效的。我如何確保filepointer計算正確?我是Java的新手,並且還沒有理解File I/O的不同方法的細節,所以如果使用BufferedWriter的話我的問題就是我正在尋找的原因,但是如何獲得當前的長度?

編輯:讀取整個文件不是一個選項。文件很大,正如我所說的,寫操作經常發生,在高峯時間每秒幾百次。

+0

可能重複:HTTP:// stackoverflow.com/questions/1625234/how-to-append -text-to-an-existing-file-in-java – ccozad

+0

@ccozad不解釋如何從我所看到的所有位置獲得位置,除非我錯過了某些東西。 (我以前見過那個頁面) – CBenni

+0

我讀到它的方式是需要將數據附加到文件中?你也說其他一切都是「低效率」。你是否假設這是因爲有人告訴你Java很慢,或者因爲你已經嘗試過並且性能不符合你的需求?社區可以幫助解決速度慢的代碼,但是當您沒有嘗試過標準的流設施時很難提供幫助。 – ccozad

回答

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.