2013-10-02 37 views
1

我想连接使用以下方法的一组文本文件。但是,只有第一个文件显示在输出文件中。使用FileChannel连接文本文件

public void concatenateFiles(List<String> fileLocations, String outputFilename){ 
try(FileChannel outputChannel = new FileOutputStream(outputFilename).getChannel()) { 
    long position = 0; 
    for(String fileLocation: fileLocations){ 
     try(FileChannel inputChannel = new FileInputStream(new File(fileLocation)).getChannel()){ 
      position += inputChannel.transferTo(position, inputChannel.size(), outputChannel); 
     } 
    } 
} catch (FileNotFoundException e) { 
    e.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 

}

你看到什么问题?

+0

起始位置我将如何解决这个问题? – locorecto

+0

这是为你编译的吗? –

+0

是的,它不会在单元测试中返回任何错误,除了输出文件不是应该的。 – locorecto

回答

3

变化

position += inputChannel.transferTo(position, inputChannel.size(), outputChannel); 

position += inputChannel.transferTo(0, inputChannel.size(), outputChannel); 

第一个参数是用于读取inputChannel

+0

所以,我真的不需要位置变量,对吧? – locorecto

+0

太棒了...这个效果很好。 – locorecto

+1

是的,对于合并文件是不必要的。 – Nicolai