Create a file with holes in it - Java File Path IO

Java examples for File Path IO:File Channel

Description

Create a file with holes in it

Demo Code

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Main {
  public static void main(String[] argv) throws IOException {
    File temp = File.createTempFile("holy", null);
    RandomAccessFile file = new RandomAccessFile(temp, "rw");
    FileChannel channel = file.getChannel();

    ByteBuffer byteBuffer = ByteBuffer.allocateDirect(100);

    putData(0, byteBuffer, channel);/*from w  ww  .  j av a2  s. co  m*/
    putData(5000000, byteBuffer, channel);
    putData(50000, byteBuffer, channel);

    // Size will report the largest position written
    System.out.println("Wrote temp file '" + temp.getPath() + "', size="
        + channel.size());

    channel.close();
    file.close();
  }

  private static void putData(int position, ByteBuffer buffer,
      FileChannel channel) throws IOException {
    String string = "location:" + position;

    buffer.clear();
    buffer.put(string.getBytes("US-ASCII"));
    buffer.flip();

    channel.position(position);
    channel.write(buffer);
  }
}

Result


Related Tutorials