Search code examples
javaiofilewriter

(Easy, nearly done) How to split text into lines from txt document and write into another text document


Code:

import javax.swing.*;
import java.io.*;
import java.util.Scanner;

public class test1 {

public static void main(String args[]) throws IOException {
    BufferedReader br = null;
    BufferedWriter bw = null;

        br = new BufferedReader(new FileReader("IRStudents.txt"));
        bw = new BufferedWriter(new FileWriter("File_2.txt"));


        String line = br.readLine();


        for (int i = 1; i <= 10 && line != null; i++) {
            bw.write(line);
            bw.write("-");
            line = br.readLine();
        }

        System.out.println("Lines are Successfully copied!");

        br.close();

        bw.close();
    }

}

}

So right now this program reads from a text file called "IRStudents.txt". The format in the IRstudenttxt document is something like:

25987 Alan
25954 Betty

However this writes into a new file like this:

25987 Alan-25954 Betty

This is wrong and I want the new text file output to look like this:

25987 Alan
-----------
25954 Betty

(Hyphens included).

Thanks very much


Solution

  • Use the function newLine() after you write a line to the Writer:

            bw.write(line);
            bw.newLine();
            bw.write("-----------");
            bw.newLine();