在 Java 中在文件中间写入字节的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/181408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best Way to Write Bytes in the Middle of a File in Java
提问by jjnguy
What is the best way to write bytes in the middle of a file using Java?
使用 Java 在文件中间写入字节的最佳方法是什么?
回答by jjnguy
Reading and Writing in the middle of a file is as simple as using a RandomAccessFilein Java.
在文件中间进行读写就像RandomAccessFile在 Java 中使用 a 一样简单。
RandomAccessFile, despite its name, is more like an InputStreamand OutputStreamand less like a File. It allows you to read or seek through bytesin a file and then begin writing over whichever bytes you care to stop at.
RandomAccessFile尽管它的名字,更像是一个InputStream,OutputStream而不是一个File。它允许您bytes在文件中读取或搜索,然后开始写入您想要停止的任何字节。
Once you discover this class, it is very easy to use if you have a basic understanding of regular file i/o.
一旦你发现了这个类,如果你对常规文件 i/o 有基本的了解,它就会很容易使用。
A small example:
一个小例子:
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();
}
回答by Adam Rosenfield
Open the file in write mode without truncating it, seek to the desired offset, and write the desired data. Just be careful about text/binary mode.
以写入模式打开文件而不截断它,寻找所需的偏移量,并写入所需的数据。请注意文本/二进制模式。
回答by Master
I think it's best to create file chunks every time. And when the file is downloaded, connect them together. Now I'm working on it.
我认为最好每次都创建文件块。下载文件后,将它们连接在一起。现在我正在努力。

