Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java OutputStream Skip (offset)

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.

like image 756
joyinside Avatar asked Mar 04 '12 21:03

joyinside


People also ask

Should I close OutputStream?

Close an OutputStreamOnce you are done writing data to a Java OutputStream you should close it.

What is difference between OutputStream and FileOutputStream?

Outputstream is an abstract class whereas FileOutputStream is the child class. It's possible that you could use Outputstream to just write in bytes for a prexisting file instead of outputting a file.

What is FileOutputStream in java?

FileOutputStream(File file) Creates a file output stream to write to the file represented by the specified File object. FileOutputStream(File file, boolean append) Creates a file output stream to write to the file represented by the specified File object.

How does OutputStream work java?

An output stream accepts output bytes and sends them to some sink. Applications that need to define a subclass of OutputStream must always provide at least a method that writes one byte of output. Methods: void close() : Closes this output stream and releases any system resources associated with this stream.


2 Answers

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
}
like image 97
vladimir e. Avatar answered Oct 12 '22 06:10

vladimir e.


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.

like image 27
Dunes Avatar answered Oct 12 '22 06:10

Dunes