TheBook
TheBook

Reputation: 1708

Write line at the end of the text document

I am trying to write line at the end of my text document but nothing is being printed at the end of the hello2.txt with this code just the hello.txt is being printed. This line last line in the text document. is not being printed at the end of the hello2.txt. How can I fix that?

I appreciate any help.

hello.txt

I am at home
how are you brother?
I am facing problem

hello2.txt Should looks like this

I am at home
how are you brother?
I am facing problem
last line in the text document.

Code:

public static void main(String[] args) {
    File file = new File("D:\\hl_sv\\hello.txt");
    try (PrintWriter writer = new PrintWriter("D:\\hl_sv\\hello2.txt");

    Scanner scanner = new Scanner(file)) {
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();

            if (line.isEmpty()) {
                System.out.println("last line in the text document");
                writer.println("last line in the text document.");
            } else {
                writer.println(line);
            }

        }

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

Upvotes: 0

Views: 122

Answers (2)

arjuns
arjuns

Reputation: 382

Also, because it looks like you want to append this line to the end of the text file, use:

writer = new PrintWriter(new FileWriter(nameOfFile, true));

In fact, simply just use the writer.append(String) method in order to add the desired String at the end of the file.

Upvotes: 2

MByD
MByD

Reputation: 137322

After the last line, while (scanner.hasNextLine()) will be evaluated to false, those not entering the loop again, and not writing the last line. You need to add the line after the loop terminates.

Upvotes: 2

Related Questions