public class Main { public static void console(Reader reader, Writer writer) throws IOException {
while (true) {
int i = reader.read();
char c = (char) i;
writer.write(c);
}
} public static void console(InputStream in, OutputStream os) throws IOException {
while (true) {
int b = in.read();
char c = (char)b;
os.write(c);
}
} public static void main(String[] args) throws Exception {
//Main.console(new InputStreamReader(System.in), new OutputStreamWriter(System.out));
//Main.console(System.in, System.out);
}
}分别执行主函数中的两个方法, 在控制台看到的结果不太一样
第一句的执行结果: 输入回车后,可以正确接收
第二句的执行结果: 输入回车后,会把之前输入的内容打印出来
这是为什么呢?

解决方案 »

  1.   

    import java.io.*;public class Main {public static void console(Reader reader, Writer writer) throws IOException {
    while (true) {
    int i = reader.read();
    char c = (char) i;
    writer.write(c);
    writer.flush();//这里加一句writer.flush()
    }
    }public static void console(InputStream in, OutputStream os) throws IOException {
    while (true) {
    int b = in.read();
    char c = (char)b;
    os.write(c);
    }
    }public static void main(String[] args) throws Exception {
    Main.console(new InputStreamReader(System.in), new OutputStreamWriter(System.out));
    //Main.console(System.in, System.out);
    }
    }
    看来OutputStreamWriter是有缓冲区的,你的字节写进去后一直保存在缓冲区了,缓冲区没满,所以你没看到结果。OutputStreamWriter具体情况请查看OutputStreamWriter的类文档,其中有“Each invocation of a write() method causes the encoding converter to be invoked on the given character(s). The resulting bytes are accumulated in a buffer before being written to the underlying output stream. The size of this buffer may be specified, but by default it is large enough for most purposes. Note that the characters passed to the write() methods are not buffered. ”就说明了底层有buffer缓冲区。