How to write a content into a file from two different files by using java.nio.files

I am trying to write content from two different files into a new file
But I am not getting the required result

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class Example2 {

    public static void main(String[] args) throws IOException {
        Path oldFile1=Paths.get("D:\\sample\\txt1.txt");
        Path oldFile2=Paths.get("D:\\sample\\txt2.txt");
        Path File=Paths.get("D:\\sample\\newFile.txt");
        Path newFile=Files.createFile(File);
            List<String> lines=Files.readAllLines(oldFile1);
            List<String> lines1=Files.readAllLines(oldFile2);


I tried this but newfile contains only the content of oldfile2

>Solution :

The Files.write() takes an optional parameter, which specifies the mode for opening the file. The default is CREATE, so you are overwriting the file each time. In your case you need:

List<String> lines=Files.readAllLines(oldFile1);
Files.write(newFile,lines, StandardOpenOption.CREATE);
List<String> lines1=Files.readAllLines(oldFile2);
Files.write(newFile,lines1,  StandardOpenOption.APPEND);

Leave a Reply