用Java编写文件中间字节的最佳方法

jjn*_*guy 17 java file java-io

使用Java在文件中间写入字节的最佳方法是什么?

jjn*_*guy 23

在文件中间读取和写入就像RandomAccessFile在Java中使用一样简单.

RandomAccessFile,尽管它的名字,更像是一个InputStreamOutputStream而不像一个File.它允许您bytes在文件中读取或搜索,然后开始写入您需要停留的任何字节.

一旦发现这个类,如果您对常规文件i/o有基本的了解,它就很容易使用.

一个小例子:

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();
}
Run Code Online (Sandbox Code Playgroud)


anj*_*anb 6

使用 RandomAccessFile