Java OutputStream Skip(offset) [英] Java OutputStream Skip (offset)

查看:105
本文介绍了Java OutputStream Skip(offset)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个函数,该函数接受File对象,偏移量和字节数组参数,并将该字节数组写入Java中的File对象。

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.

所以函数看起来像

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

但问题是offset参数是long类型,所以我不能使用OutputStream的write()函数,它接受整数偏移。

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.

与跳过(长)的InputStream不同,似乎OutputStream无法跳过文件的第一个字节。

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?

谢谢。

推荐答案

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
}

这篇关于Java OutputStream Skip(offset)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆