2012-05-03 35 views
2

我想用另一個字節數組「覆蓋」或「切換」一些字節(比如文件的前2048個字節),大小爲100MB。
我不想閱讀整個文件,因爲需要批評時間才能瀏覽整個文件。編輯一個文件而不需要遍歷整個字節緩衝區?

我試過到目前爲止:

FileOutputStream out = new FileOutputStream(file); 

out.getChannel().write(buffer, position); 

新緩衝區數組是相同的尺寸。

我正在用java + eclipse開發Android應用程序,需要這些。
如果有人能給我寫一段代碼來完成這項工作,我會很高興。

在此先感謝。

+0

我們不會爲您編寫代碼,但會嘗試幫助解決您嘗試過的任何操作。 –

+0

@Marc B:謝謝,我已經將它添加到問題的正文 –

+0

這是不可能的。 –

回答

2

這個覆蓋該文件的前2048個字節與data數組的內容。

final RandomAccessFile file = new RandomAccessFile(filename, "rw"); 
final FileChannel channel = file.getChannel(); 
final byte[] data = new byte[2048];   // lets say it's got the data you want 
final ByteBuffer buff = ByteBuffer.wrap(data); 

channel.position(0);       // (we were already here, but as an example) 
channel.write(buff);       // writes the entire 2028 bytes from buff 
channel.force(false);      // (superfluous if you close() afterwards) 
channel.close();        // close the file descriptor 
+0

謝謝,我會在一秒鐘內嘗試,如果真的有效,就會給你名聲。 –

+0

@TalKanel:我不確定自己做了什麼與你似乎做的不同 - 但這是要做到這一點... –

+0

@TalKanel:我已經做了一個修改來修復一些錯別字。 –

相關問題