質問

import java.io.*;
class demo
{
public static void main(String args[])
{
    PrintWriter pw=new PrintWriter(System.out);
    pw.println("java");
    //pw.print("java");
}
}

// the output is java using pw.println but output is null using pw.print i.e nothing gets printed on console while using print.

役に立ちましたか?

解決

Try this instead :

PrintWriter pw=new PrintWriter(System.out);
pw.print("java");
pw.flush();

The PrintWriter is going to be doing internal buffering, and the println method is automatically flushing it.

他のヒント

It's almost certainly just buffering - and as you're not flushing it, you never get the output. From the docs:

Unlike the PrintStream class, if automatic flushing is enabled it will be done only when one of the println, printf, or format methods is invoked, rather than whenever a newline character happens to be output. These methods use the platform's own notion of line separator rather than the newline character.

Try:

pw.flush();

at the end of the code.

For automatic flushing, you could use this constructor

PrintWriter(OutputStream out, boolean autoFlush);

A call to println() implicitly flushes the output buffer whereas a call to print() does not. Try using print() and then call pw.flush().

Note also that there are constructors of PrintWriter which include an option to automatically flush after any write call.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top