簡體   English   中英

如何使用transferFrom連接Java中的兩個文件

[英]How to concatenate two files in Java using transferFrom

下面是我的代碼。 我是否正確地注意到transferFrom不會修改要傳輸到的通道的位置?

這是行不通的。 它只是復制第一個文件。

問候。

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中使用position參數

  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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM