gpt4 book ai didi

java - 当 Inputstream 中没有数据时跳过在 FileOutputStream 中创建文件

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:28:24 24 4
gpt4 key购买 nike

这是一个日志功能,它记录来自外部程序执行的错误流。一切正常。但是我不想在错误流中没有数据时生成日志文件。目前它正在创建零大小的文件。请帮忙。

FileOutputStream fos = new FileOutputStream(logFile);
PrintWriter pw = new PrintWriter(fos);

Process proc = Runtime.getRuntime().exec(externalProgram);

InputStreamReader isr = new InputStreamReader(proc.getErrorStream());
BufferedReader br = new BufferedReader(isr);
String line=null;
while ( (line = br.readLine()) != null)
{
if (pw != null){
pw.println(line);
pw.flush();
}
}

谢谢。

最佳答案

简单地推迟 FileOutputStreamPrintWriter 的创建,直到您需要它:

PrintWriter pw = null;

Process proc = Runtime.getRuntime().exec(externalProgram);

InputStreamReader isr = new InputStreamReader(proc.getErrorStream());
BufferedReader br = new BufferedReader(isr);
String line;
while ( (line = br.readLine()) != null)
{
if (pw == null)
{
pw = new PrintWriter(new FileOutputStream(logFile));
}
pw.println(line);
pw.flush();
}

就我个人而言,我不是 PrintWriter 的忠实粉丝 - 它只是吞没所有异常这一事实让我担心。我还会使用 OutputStreamWriter 以便您可以明确指定编码。无论如何,这与这里的真正问题无关。

关于java - 当 Inputstream 中没有数据时跳过在 FileOutputStream 中创建文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3334854/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com