Skip to content

Writing multiple lines using PrintWriter in Java

I am sorry if this question is already answered on the internet but by looking at the ‘similar questions’ I couldn’t find an answer for my problem. So basically I’m trying to understand why using PrintWriter to write lines of text into a file apparently skips the first line every 2 lines I give.

This is the method I use in its own class:

public class IO_Utilities {

public static void Write(String outputName){

    PrintWriter outputStream = null;
    try {
        outputStream = new PrintWriter(outputName);
    } catch (FileNotFoundException e) {
        System.out.println(e.toString());
        System.exit(0);
    }
    System.out.println("Write your text:");
    Scanner user = new Scanner(System.in);
    while(!user.nextLine().equals("stop")) {
        String line = user.nextLine();
        outputStream.println(line);
    }
    outputStream.close();
    user.close();
    System.out.println("File has been written.");
}

When I call it from main with:

IO_Utilities.Write("output.txt");

and write:

first line
second line
third line
stop
stop

The output text is actually:

second line
stop

I am sure the problem is the while loop, because if I input the lines manually one by one it works correctly, but I don’t understand exactly why it behaves like it does right now.

Answer

while(!user.nextLine().equals("stop")) {
        String line = user.nextLine();
        outputStream.println(line);
    }

You repeat your user.nextLine(); within your loop, so line is not the same as the one you compare to “stop”.

Rewrite that part as:

String line = user.nextLine();
while( !line.equals("stop")) {
  outputStream.println(line);
  line = user.nextLine();
}