0

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();
    }
}
TheBook
  • 1,508
  • 1
  • 11
  • 29

2 Answers2

2

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.

arjuns
  • 247
  • 1
  • 8
2

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.

MByD
  • 129,681
  • 25
  • 254
  • 263
  • 1
    @Tom - you're right, I'm not familiar with Java7 features enough. Thanks! – MByD Jun 08 '15 at 18:07
  • This is the good thing about the try-with-resources Statement ... we can't forget to close the resource properly :D. – Tom Jun 08 '15 at 18:08