简体   繁体   English

Java OutputStream Skip(offset)

[英]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. 我正在尝试编写一个函数,它接受File对象,偏移量和字节数组参数,并将该字节数组写入Java中的File对象。

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. 但问题是offset参数是long类型,所以我不能使用OutputStream的write()函数,它将整数作为偏移量。

Unlike InputStream, which has skip(long), it seems OutputStream has no way to skip the first bytes of the file. 与跳过(长)的InputStream不同,似乎OutputStream无法跳过文件的第一个字节。

Is there a good way to solve this problem? 有没有好办法解决这个问题?

Thank you. 谢谢。

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
}

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. 使用输入流,您只是说您要丢弃前n个字节的数据。 However, with an OutputStream something must be written to stream. 但是,使用OutputStream必须将某些内容写入流。 You can't just ask that the stream pretend n bytes of data were written, but not actually write them. 你不能只是要求流假装写入n个字节的数据,而不是实际写入它们。 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. 解决方案:使用FileChannelsRandomAccessFile insteead。

If you want to write at the end of the file then use the append mode (FileOutputStream(String name, boolean append)). 如果要在文件末尾写入,请使用追加模式(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). 在我看来,FileOutputStream中应该有一个skip方法,但是现在你想要前往文件中的特定位置进行写入,那么你必须使用可搜索的FileChannel或RandomAccessFile(因为它是其他人提到的)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM