【问题标题】:I created a PrintWriter with autoflush on; why isn't it autoflushing?我创建了一个带有 autoflush 的 PrintWriter;为什么不自动刷新?
【发布时间】:2010-11-17 11:29:05
【问题描述】:

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

这是服务器端代码。问题出在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());
        }
    }
}

我是否在使用

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

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

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

out.flush() ;

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

【问题讨论】:

    标签: java io flush printwriter


    【解决方案1】:

    来自Javadocs

    参数:

    out - 输出流
    autoFlush - 布尔值;如果为真,printlnprintfformat 方法将刷新输出缓冲区

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

    【讨论】:

    • 我按照你的建议试过了,它正在工作。因此,只有 println 被认为是刷新和写入,而 print 不会。文档中没有提到哪些方法与自动刷新兼容,哪些不兼容。那么,一个人是怎么知道这一点的。 :)
    • 在文档中提到的,只是不适用于个别方法。
    • 但是 write、print、printf 和 println 的重载方法太多了。 1 如何知道哪个 1 与 autoflushing 兼容,或者只有以 ln 结尾的方法才支持 autoflushing。
    • 我刚刚查看了 Javadocs。直到我在研究您的问题时看到它才知道。
    • 这是一个可怕的实现!在 printWriter 上设置 autoFlush 不会导致它 autoFlushing!。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-23
    • 1970-01-01
    • 1970-01-01
    • 2013-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多