Frank L
Frank L

Reputation: 29

Reading from text file line by line in Java

How I can read the content from a text file line by line? When I try to output the content, the newline character seems to be ignored from reading.

public class ReadFile {
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        String str= "";

        //Reading content from file
        Scanner in = new Scanner(new FileReader("text.txt"));
        while(in.hasNextLine()){
            str = str + in.nextLine();
            str.concat("\n");      //Not working!!!!!!!!!!!
        }

        in.close();

        //Writing content to another file
        PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
        out.println(str);
        out.close();
    }
}

Upvotes: 2

Views: 158

Answers (3)

Hari Krishna
Hari Krishna

Reputation: 3568

You are making mistake in the following line:

str.concat("\n"); 

Update it like below:

str = str.concat("\n"); 

I am giving updated program.

public class ReadFile {

    public static void main(String[] args) throws IOException {
        try (PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
                Scanner in = new Scanner(new FileReader("text.txt"));) {
            while (in.hasNextLine()) {
                out.println(in.nextLine());
            }
        }
    }
}

Upvotes: 2

thepiyush13
thepiyush13

Reputation: 1331

You are concatenating string which is not very efficient; use StringBuilder, also use platform independent line terminator.

Try this instead :

public class ReadFile {

    public static void main(String[] args) throws IOException {

        String str= "";

        //Reading content from file
        Scanner in = new Scanner(new FileReader("text.txt"));
        StringBuilder str  = new StringBuilder();
        String newLine = System.getProperty("line.separator");
        while(in.hasNextLine()){            
            str.append(in.nextLine()).append(newLine);
        }

        in.close();

        //Writing content to another file
        PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
        out.println(str.toString());
        out.close();
    }
}

Upvotes: -2

ManoDestra
ManoDestra

Reputation: 6503

You need to set the string to the new value after your concat operation.

str = str.concat("\n"); // or \r\n for Windows.

Upvotes: 1

Related Questions