0

My requirement is to copy the content from one master file and paste it in temp file. These files are in .dat file format. The code copy paste the contents perfectly but it comes in one single line. My need is, it should come in new lines instead of one single line.

public static void JavaCopyFile () {

try {
    FileReader fr = new FileReader("C:\\Automation\\Master_Template.dat");
    BufferedReader br = new BufferedReader(fr);
    FileWriter fw = new FileWriter("C:\\Automation\\Temp.dat");
    String s;

    while ((s = br.readLine()) != null) { // read a line
        fw.write(s); // write to output file
        fw.flush();
    }
    br.close();
    fw.close();
                System.out.println("file copied");
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
Raj
  • 1
  • 2
  • What is .dat file format, do you mean it is a text file with the extension .dat? Also, why not use one of the copy methods in `java.nio.file.Files`? – Joakim Danielson May 29 '21 at 16:46

1 Answers1

0

Please use

writer.write(System.getProperty( "line.separator" ));

to add new line character(s) specific for the OS you use. Also there is no need to flush after each line - one time at the very end is sufficient:

.......
newLine = writer.write(System.getProperty( "line.separator"));
while ((s = br.readLine()) != null) { // read a line
    fw.write(s); // write to output file
    fw.write(newLine);
}
fw.flush();
.......

Check this link for other solutions: Create a new line in Java's FileWriter