java - 如何使用transferFrom在Java中连接两个文件

标签 java file nio filechannel

下面是我的代码。我是否正确地注意到,transferFrom 不会修改要传输到的 channel 的位置?

这不起作用。它只是复制第一个文件。

问候。

File file1 = new File(binDirectory + "/file1.avi");
File file2 = new File(binDirectory + "/file2.avi");
File fileo = new File(binDirectory + "/concatenatedfile.avi");

long time1 = System.currentTimeMillis();

FileInputStream is1 = new FileInputStream(file1);
FileInputStream is2 = new FileInputStream(file2);
FileOutputStream os = new FileOutputStream(fileo);

FileChannel fc1 = is1.getChannel();
FileChannel fc2 = is2.getChannel();
FileChannel fco = os.getChannel();

fco.transferFrom(fc1, 0, fc1.size());

/*
 * This method (transferFrom) does not modify this channel's position. If the given position
 * is greater than the file's current size then no bytes are transferred. If
 * the source channel has a position then bytes are read starting at that position
 * and then the position is incremented by the number of bytes read. 
 */
fco.position(fc1.size());

fco.transferFrom(fc2, 0, fc2.size());

fc1.close();
fc2.close();
fco.close();

is1.close();
is2.close();
os.close();

long time2 = System.currentTimeMillis();
System.out.println("Time taken: " + (time2-time1)  +" ms");    

最佳答案

问题是您在第二次传输操作中明确使用了 0 的起始位置。您需要在 transferFrom 中使用位置参数像这样

  fco.transferFrom(fc1, 0, fc1.size());
  // fco.position(fc1.size()); <-- unneeded.
  // fco.transferFrom(fc2, 0, fc2.size()); <-- 2nd parameter is the source of your bug.
  fco.transferFrom(fc2, fc1.size() - 1, fc2.size()); // <-- check with your input. 
                                                     // I did a Hello world test.

关于java - 如何使用transferFrom在Java中连接两个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20916111/

相关文章:

Java NIO(Netty): Exceptionhandling in Downstream Hanlders/Chain

java - 如何使用 FileChannel 和 ByteBuffer 从文件中写入和读取 Java 对象中的字符串属性

file - 如何将文本文件加载到 Lua 中的某种类似表格的变量中?

Java 重用套接字

java - 查找并打印 10000 以下的完全数(Liang,Java 简介,练习 5.33)

java - 为什么枚举可以有包私有(private)构造函数?

java - JAX-RS POST 文件输入流为空

java - 为什么 getNextZipEntry 会跳过几个文件的根目录?

Java NIO select() 返回时没有选择键 - 为什么?

java - 通用接口(interface)数组