简体   繁体   English

使用FileChannel连接文本文件

[英]Concatenate text files using FileChannel

I am trying to concatenate a set of text files using the following method. 我试图使用以下方法连接一组文本文件。 However, only the first file is show in the output file. 但是,只有第一个文件显示在输出文件中。

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();
}

} }

Do you see any problems? 你看到有什么问题吗?

Change 更改

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

to

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

The first parameter is a start position for reading inputChannel 第一个参数是读取inputChannel的开始位置

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM