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

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

问题描述

解决方案

在文本中使用Java编写字节的最佳方式是什么?文件中间与使用 <$ c一样简单$ c> RandomAccessFile



RandomAccessFile 尽管它的名字,更像是一个 InputStream OutputStream 而不像文件。它允许您通过文件中的字节读取或查找,然后开始写入您要停止的任何字节。



一旦你发现这个课程,如果你对普通档案i / o有一个基本的了解,那就很容易使用。



一个小例子:

  public static void aMethod(){
RandomAccessFile f = new RandomAccessFile(new File(whereDidIPutTHatFile),rw) ;
long aPositionWhereIWantToGo = 99;
f.seek(aPositionWhereIWantToGo); //这基本上读取文件中的n个字节
f.write(Im in teh fil,writn bites.getBytes());
f.close();
}


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

解决方案

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();
}

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

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