将数据字节写入java中偏移量的文件

时间:2013-03-27 07:01:09

标签: java file

我希望将数据写入不同偏移量的文件。例如,在第0个位置,在(第(2)个位置,在(第(4)个位置等处)大小表示要创建的文件的文件大小。这可能不创建不同的文件部分并加入它们吗?

3 个答案:

答案 0 :(得分:6)

您可以使用RandomAccessFile在文件中随意写信 - 只需使用seek即可到达正确的位置,然后开始写作。

但是,这不会在那些地方插入字节 - 它只会覆盖它们(或者如果你写的是结尾的话,最后添加数据)当然是当前的文件长度)。目前尚不清楚这是否是你想要的。

答案 1 :(得分:0)

您要找的是Random access files。来自official sun java tutorial site -

  

随机访问文件允许对a的非顺序或随机访问   文件的内容。要随机访问文件,请打开文件,查找   特定位置,读取或写入该文件。

     

使用SeekableByteChannel界面可以实现此功能。   SeekableByteChannel接口使用概念扩展了通道I / O.   当前的位置。方法使您可以设置或查询   位置,然后您可以从中读取数据或将数据写入,   那个位置。 API由一些易于使用的方法组成:

     

position - 返回通道的当前位置
  position(long) - 设置通道的位置
  read(ByteBuffer) - 从通道
读取缓冲区中的字节   write(ByteBuffer) - 将缓冲区中的字节写入通道
  truncate(long) - 截断连接到通道的文件(或其他实体)

和一个例子,在那里提供 -

String s = "I was here!\n";
byte data[] = s.getBytes();
ByteBuffer out = ByteBuffer.wrap(data);

ByteBuffer copy = ByteBuffer.allocate(12);

try (FileChannel fc = (FileChannel.open(file, READ, WRITE))) {
    // Read the first 12
    // bytes of the file.
    int nread;
    do {
        nread = fc.read(copy);
    } while (nread != -1 && copy.hasRemaining());

    // Write "I was here!" at the beginning of the file.
    // See how they are moving back to the beginning of the
    // file?
    fc.position(0);
    while (out.hasRemaining())
        fc.write(out);
    out.rewind();

    // Move to the end of the file.  Copy the first 12 bytes to
    // the end of the file.  Then write "I was here!" again.
    long length = fc.size();

    // Now see here. They are going to the end of the file.
    fc.position(length-1);

    copy.flip();
    while (copy.hasRemaining())
        fc.write(copy);
    while (out.hasRemaining())
        fc.write(out);
} catch (IOException x) {
    System.out.println("I/O Exception: " + x);
}

答案 2 :(得分:0)

如果这不是一个巨大的文件,你可以阅读整个文件而不是编辑数组:

public String read(String fileName){
    BufferedReader br = new BufferedReader(new FileReader(fileName));
    try {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            sb.append(line);
            sb.append("\n");
            line = br.readLine();
        }
        String everything = sb.toString();
    } finally {
        br.close();
    }
}

public String edit(String fileContent, Byte b, int offset){
    Byte[] bytes = fileContent.getBytes();
    bytes[offset] = b;
    return new String(bytes);
]

然后将其写回文件(或者只删除旧文件并将字节数组写入具有相同名称的新文件)

相关问题