2013-03-27 53 views
6

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

+1

转到[这里](http://docs.oracle.com/javase/tutorial/essential/io/rafs.html)。 – 2013-03-27 07:03:29

回答

6

那么你可以使用RandomAccessFile写信给你喜欢的任何地方 - 只需使用seek来到正确的位置并开始写作。

然而,这不会在那些地方插入字节 - 它只是覆盖他们(或者在末尾添加数据如果你正在写过去的当前文件长度的目的,当然)。目前还不清楚这是否是你想要的。

0

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

随机访问文件允许一个 文件的内容不连续,或随机访问。要随机访问文件,请打开文件,查找特定位置,然后读取或写入该文件。

SeekableByteChannel接口可以实现此功能。 SeekableByteChannel接口扩展了当前位置的概念 的通道I/O。通过方法,您可以设置或查询 的位置,然后您可以从该位置读取数据或将数据写入 。 API包含了几下,简单易用,方法:

位置 - 返回通道的当前位置
位置(长) - 设置通道的位置
读(字节缓冲区) - 读取字节到从通道缓冲区
写(字节缓冲区) - 将字节从缓冲器到通道
截断(长) - 截断连接到通道

和示例的文件(或其他实体),它有提供 -

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

,然后将它写回文件(或只是删除旧的和写将字节数组转换为同名的新文件)