使用Java在文件中间写入字节的最佳方法是什么?
在文件中间进行读写就像在Java中使用RandomAccessFile
一样简单。
RandomAccessFile
,尽管有其名称,但更像RandomAccessFile
和RandomAccessFile
,而不像InputStream
。它允许您读取或搜索文件中的OutputStream
,然后开始写您想停在的任何字节。
一旦发现了此类,如果您对常规文件的输入/输出有基本的了解,它将非常容易使用。
一个小例子:
File
使用bytes
public static void aMethod(){
RandomAccessFile f = new RandomAccessFile(new File("whereDidIPutTHatFile"), "rw");
long aPositionWhereIWantToGo = 99;
f.seek(aPositionWhereIWantToGo); // this basically reads n bytes in the file
f.write("Im in teh fil, writn bites".getBytes());
f.close();
}
RandomAccessFile
以写模式打开文件而不被截断,寻找到所需的偏移量,然后写入所需的数据。请注意文本/二进制模式。
我认为最好每次都创建文件块。下载文件后,将它们连接在一起。现在我正在研究它。