Java OutputStream Skip (offset)
Asked Answered
A

3

10

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.

Audible answered 4/3, 2012 at 21:30 Comment(4)
The largest number you can put in an int is 2,147,483,647. Are the arrays you want to write larger than +- 2GB?Diploblastic
Just for clarification: the offset only applies to the position in the array, not the output stream, right? With an OutputStream you can not skip positions.Diploblastic
@TheNail offset refers to the offset from the beginning of the file, not the beginning of the array. And unless you are using FAT as a file system you can indeed have files larger than 2Gb.Balfore
Ah, FYI: the int offset parameter off in OutputStream.write() is about the array, not the stream/file (but I see there are some relevant answers already).Diploblastic
V
17
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
}
Vernal answered 4/3, 2012 at 21:44 Comment(0)
B
5

That's to do with the semantics of the streams. With an input stream you are just saying that you are discarding the first n bytes of data. However, with an OutputStream something must be written to stream. You can't just ask that the stream pretend n bytes of data were written, but not actually write them. The reason for this is because not all streams will be seekable. Data coming over a network is not seekable -- you get the data once and only once. However, this is not so with files because they are stored on a hard drive and it is easy to seek to any position on the hard drive.

Solution: Use FileChannels or RandomAccessFile insteead.

Balfore answered 4/3, 2012 at 21:39 Comment(0)
L
1

If you want to write at the end of the file then use the append mode (FileOutputStream(String name, boolean append)). In my humble opinion, there should be a skip method in the FileOutputStream, but for now you if you want to travel to a specific location in a file for writing then you have to use the seek-able FileChannel or the RandomAccessFile (as it was mentioned by others).

Lightfoot answered 8/2, 2016 at 3:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.