在 Java 中在文件中间写入字节的最佳方法 [英] Best Way to Write Bytes in the Middle of a File in Java

查看:33
本文介绍了在 Java 中在文件中间写入字节的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

在文件中间读写就像使用 RandomAccessFile 在 Java 中.

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

RandomAccessFile,尽管它的名字,更像是一个 InputStreamOutputStream 而不太像一个 File.它允许您读取或查找文件中的 bytes,然后开始写入您想要停止的任何字节.

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.

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

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

这篇关于在 Java 中在文件中间写入字节的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆