【问题标题】:BufferedWriter stops writing after some timeBufferedWriter 在一段时间后停止写入
【发布时间】:2019-01-03 11:46:41
【问题描述】:

我正在开发一种日志记录功能,其中我将记录文本添加到队列中,然后将日志写入文件。写法如下:

private void writeLogs(File logFile, String logText) {
    try {
        if (logFile == null || !logFile.exists() || logText == null || logText.isEmpty()) {
            return;
        }
        synchronized (lock) {
            BufferedWriter buf = null;
            FileOutputStream fos = null;
            if (megabytesAvailable(logFile) > 5) {
                try {

                    buf = new BufferedWriter(new FileWriter(logFile, true));
                    buf.append(logText);
                    Log.e("writeLogs", logText);
                    buf.append("\r\n");
                    //buf.newLine();
                } catch (Exception e) {
                    Log.e("writeLog", "e", e);
                } finally {
                    buf.flush();
                    buf.close();
                }
            }
        }
    } catch (Exception ex) {
        Log.e("writeLogs1","E",ex);
    }

}

它工作了一段时间,然后突然停止写入文件。 最后打印的日志总是发送原始文本的一半。 SO中的所有问题都指向“冲洗”,但正如您所见,我已经冲洗了作家。我错过了什么?将文本添加到队列的方法和writeLogs 的调用方法是同步的。起初我认为这与线程死锁有关,但系统每次都会打印log.e,这意味着缓冲写入获取文本但无法写入。有什么帮助吗?

这是打印文件内容的方法:

public void printLogFileContent(){ /** Only for testing purpose **/
    BufferedReader br = null;
    try {
        br = new BufferedReader(new FileReader(logFile.getAbsolutePath()));
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();
        while (line != null) {
            sb.append(line);
            sb.append("\n");
            line = br.readLine();
        }
        Log.e("printLogFileContent",sb.toString());
    } catch (FileNotFoundException e) {
        Log.e("FileNoF","E",e);
    } catch (IOException e) {
        Log.e("IOE","E",e);
    } finally {
        try {
            br.close();
        } catch (IOException e) {
            Log.e("IOE2","E",e);
        }
    }
}

【问题讨论】:

    标签: android thread-safety java-io bufferedwriter


    【解决方案1】:

    这是一件非常愚蠢的事情。实际上,“Log.e”一次可以打印的字符数是有限制的。那已经筋疲力尽了。这就是为什么我只看到一半的日志。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-19
      • 2018-05-24
      相关资源
      最近更新 更多