Question

I have a question regarding to printWriter, please see code below:

PrintWriter out = new PrintWriter(System.out);
Scanner n = new Scanner(System.in);

while (n.hasNext()) {
    String str = n.next();
    if (str.equals("m")) {
        break;
    } else {
        out.printf("%s", str);
        out.print(" ");
    }   
}
n.close();
// out.close();
System.out.println("input is successful");

When I input something by keyboard, it output on screen what i input, but it did not process the rest of the program, which meant it did not print "input is successful", however, when I delete the command of out.close(); it kept running the rest program, so I want to ask what does out.close() mean? I thought it just means to stop writing for output, I guess it has something to do with the parameter I put in the new PrintWriter(...)

Was it helpful?

Solution

PrintWriter.close() will also close the underlying stream, i.e. System.out. This effectively means that any subsequent outputs to System.out will be ignored.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top