简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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