刷新BufferedWriter仅在调试时有效

时间:2014-05-25 08:01:33

标签: java debugging flush bufferedwriter

我目前正在使用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执行它时才能使用刷新。即使我把秒表放在下一行,它也不再有效。

我无法弄清楚这类问题。

1 个答案:

答案 0 :(得分:0)

每当打开输出流和套接字等可关闭资源时,都应该尝试使用资源或尝试使用finally块。你根本没有关闭你的流,你基本上是在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");
  }
}