java 我创建了一个带有自动刷新的 PrintWriter;为什么不自动刷新?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1240968/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 15:46:31  来源:igfitidea点击:

I created a PrintWriter with autoflush on; why isn't it autoflushing?

javaioflushprintwriter

提问by mogli

My client is a web browser, and sending request to myserver using this url: http://localhost

我的客户端是一个网络浏览器,并使用这个 url 向 myserver 发送请求: http://localhost

This is the server side code. The problem lies in the run method of the ServingThreadclass.

这是服务器端代码。问题出在ServingThread类的run方法上。

class ServingThread implements Runnable{
    private Socket socket ;

    public ServingThread(Socket socket){
        this.socket = socket ;
        System.out.println("Receives a new browser request from "
                      + socket + "\n\n");
    }

    public void run() {
        PrintWriter out = null ;

        try {
            String str = "" ;
            out = new PrintWriter( socket.getOutputStream() ) ;
            out.write("This a web-page.") ;
            // :-(
            out.flush() ;
            // :-(
            socket.close() ;
            System.out.println("Request successfully fulfilled.") ;
        } catch (IOException io) {
            System.out.println(io.getMessage());
        }
    }
}

Whether I am using

我是否正在使用

out = new PrintWriter( socket.getOutputStream(), true ) ;

or

或者

out = new PrintWriter( socket.getOutputStream() ) ;

the output is not coming to the browser. Output is coming to the browser only if I am manually flushing using stream using

输出没有进入浏览器。仅当我使用流手动刷新时才会输出到浏览器

out.flush() ;

My question:new PrintWriter( socket.getOutputStream(), true )is supposed to automatically flush the output buffer, but it's not doing so. Why?

我的问题:new PrintWriter( socket.getOutputStream(), true )应该自动刷新输出缓冲区,但它没有这样做。为什么?

回答by Michael Myers

From the Javadocs:

Javadocs

Parameters:

out- An output stream
autoFlush- A boolean; if true, the println, printf, or formatmethods will flush the output buffer

参数:

out- 一个输出流
autoFlush- 一个布尔值;如果为 true,println, printf, 或format方法将刷新输出缓冲区

It does not say that write()will flush the output buffer. Try using println()instead and it should flush like you expect it to.

它并没有说write()会刷新输出缓冲区。尝试println()改用它,它应该像您期望的那样冲洗。