【问题标题】:Flush of BufferedWriter only works when debuggingBufferedWriter 的刷新仅在调试时有效
【发布时间】:2014-05-25 08:01:32
【问题描述】:

我目前正在做一个 java 项目。

我在服务器类中有一个方法,它将输入字符串发送到特定的套接字。

    private void inviaSingoloGiocatore(Giocatore giocatore, String outputString) throws DisconnessoGiocatoreCorrenteException {
    long beforeTime = System.currentTimeMillis();
    long elapsedTime = 0;
    boolean freezed = false;
    while (TIMER - elapsedTime > 0){
        try {
            Socket socket = sockets[giocatore.getIndice()];
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            outputString += "\n";
            out.write(outputString);
            out.flush();
            return;
        } catch (IOException e) {
            if(!freezed){
                inviaTuttiGiocatori(encoder.freeze(giocatore)); //Freeze
                freezed = true;
            }
        }
        elapsedTime = System.currentTimeMillis()-beforeTime;
    }
    inviaTuttiGiocatori(encoder.disconnesso(giocatore));//disconnesso
    throw new DisconnessoGiocatoreCorrenteException();
}

问题是刷新仅在我使用调试工具秒表并按 f6 执行时才有效。即使我把秒表放在下一行,它也不再起作用了。

我无法弄清楚这种问题。

【问题讨论】:

    标签: java debugging flush bufferedwriter


    【解决方案1】:

    当您打开可关闭的资源(如输出流和套接字)时,您应该对资源使用 try 或对 finally 块使用 try。你根本没有关闭你的流,你基本上是在 while 循环中泄漏文件句柄。

    所以在你的 while 循环中这样的事情可能会工作得更好。块退出后,try 会自动关闭您的资源。这也应该照顾冲洗。您应该在 OutputStreamWriter 上设置字符编码。此代码在某些平台上会错误处理 UTF-8:

    try(Socket socket = sockets[giocatore.getIndice()]) {
      try(BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), Charset.forName("UTF8")))) {
        out.write("whatever it is you wanted to write, outputString was not defined");
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-21
      • 1970-01-01
      • 1970-01-01
      • 2017-01-03
      • 1970-01-01
      • 2018-11-10
      • 2017-01-30
      • 2019-08-22
      相关资源
      最近更新 更多