Best Way to Write Bytes in the Middle of a File in Java

风格不统一 提交于 2019-11-26 05:36:31

问题


What is the best way to write bytes in the middle of a file using Java?


回答1:


Reading and Writing in the middle of a file is as simple as using a RandomAccessFile in Java.

RandomAccessFile, despite its name, is more like an InputStream and OutputStream and less like a File. It allows you to read or seek through bytes in a file and then begin writing over whichever bytes you care to stop at.

Once you discover this class, it is very easy to use if you have a basic understanding of regular file 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();
}



回答2:


Use RandomAccessFile

  • Tutorial
  • Javadocs



回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/181408/best-way-to-write-bytes-in-the-middle-of-a-file-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!