Java OutputStream Skip (offset)

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

So the function will look like

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

But the problem is that the offset parameter is long, so I cannot use the write () function for the OutputStream, which takes an integer as an offset.

Unlike an InputStream, which has a gap (long), it seems that the OutputStream is not able to skip the first bytes of the file.

Is there a good way to solve this problem?

Thanks.

+6
source share
3 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 } 
+11
source

What to do with the semantics of threads. With the input stream, you simply say that you discard the first n bytes of data. However, with an OutputStream, something needs to be written to the stream. You cannot just ask a stream to look like n bytes of data, but not write them. The reason for this is that not all threads will be searchable. Data arriving over the network is not available for search - you receive data once and only once. However, this is not the case with files, because they are stored on the hard disk, and it is easy to find any position on the hard disk.

Use FileChannels or RandomAccessFile insteead.

+4
source

If you want to write at the end of the file, use the add mode (FileOutputStream (line name, boolean append)). In my humble opinion, there should be a skip method in FileOutputStream, but for now you want you to go to a specific place in the file for writing, you need to use File File File File (FileChannel) or RandomAccessFile (as others mentioned). A.

+1
source

Source: https://habr.com/ru/post/909958/


All Articles