Java OutputStream Skip (offset)

泄露秘密 提交于 2019-11-30 19:34:44
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
}
Dunes

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.

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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!