2013-03-27 18 views
6

異なるオフセットでファイルにデータを書きたいと思っています。例:0番目の位置、(size/2)番目の位置、(size/4)番目の位置などsizeは作成するファイルのファイルサイズを表します。これは、異なるファイルパーツを作成して結合することなく可能ですか?データバイトをJavaのオフセットでファイルに書き込む

+1

[こちら](http://docs.oracle.com/javase/tutorial/essential/io/rafs.html)。 –

答えて

6

まあ、RandomAccessFileを使用してファイルを好きな場所に書き込むことができます - ちょうどseekを使って適切な場所に移動して書き込みを開始してください。

しかし、これはは、それらの場所でバイトを挿入しません - それはちょうど彼ら(またはあなたはもちろん、現在のファイル長の終わりを過ぎて書いている場合は、最後にデータを追加)を上書きします。それがあなたが望んでいるかどうかは明らかではありません。

0

あなたが探しているものはRandom access filesです。

ランダムアクセスファイル ファイルの内容に、非シーケンシャル、またはランダムアクセスを許可 - official sun java tutorial siteから。ランダムにファイルにアクセスするには、ファイルを開き、 特定の場所を探し、そのファイルの読み書きを行います。

この機能は、SeekableByteChannelインターフェイスで使用できます。 SeekableByteChannelインターフェイスは、現在位置の概念 でチャネルI/Oを拡張します。メソッドを使用すると、 の位置を設定または問い合わせることができ、その場所からデータを読み取ったり、その場所にデータを書き込んだりすることができます。 APIは、いくつかの、使いやすい方法で構成されています - チャンネルの現在位置を返します
位置(ロング) - チャネルの位置
読み取り(のByteBuffer)がセット -

位置チャネルからバッファへバイトを読み込み
ライト(のByteBuffer) - チャネルにバッファからバイトを書き込み
TRUNCATE(長い) - ファイル(または他のエンティティ)を切り捨てチャネル

とが設けられている例、に接続された -

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

、ファイルに書き戻す(または単に古いものを削除して、書き込みバイト配列を同じ名前の新しいファイルに変換)

関連する問題