Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.io.IOException;
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);
            Files.write(newFile,lines);
          
            List<String> lines1=Files.readAllLines(oldFile2);
            Files.write(newFile,lines1);
        
    }

}

I tried this but newfile contains only the content of oldfile2

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading