Java OutputStream Skip (offset)

so_ju picture so_ju · Mar 4, 2012 · Viewed 10.7k times · Source

I am trying to write a function that takes File object, offset and byte array parameters and writes that byte array to a File object in Java.

So the function would look like

public void write(File file, long offset, byte[] data)

But the problem is that the offset parameter is long type, so I can't use write() function of OutputStream, which takes integer as an offset.

Unlike InputStream, which has skip(long), it seems OutputStream has no way to skip the first bytes of the file.

Is there a good way to solve this problem?

Thank you.

Answer

vladimir e. picture vladimir e. · Mar 4, 2012
try {
   FileOutputStream out = new FileOutputStream(file);
   try {
       FileChannel ch = out.getChannel();
       ch.position(offset);
       ch.write(ByteBuffer.wrap(data));
   } finally {
       out.close();
   } 
} catch (IOException ex) {
    // handle error
}