Question

Below is my code. Have I correctly noted that transferFrom does not modify the position of the channel being transferred to?

This does not work. It just copies the first file.

Regards.

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");    
Was it helpful?

Solution

The problem is you're explicitly using a start position of 0 in your second transfer operation. You need to use the position argument in transferFrom like so

  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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top