当Inputstream中没有数据时跳过在FileOutputStream中创建文件
这是一个日志记录功能,用于记录外部程序执行过程中的错误流。一切正常。但我不想在错误流中没有数据时生成日志文件。目前它正在创建零大小的文件。请帮忙。
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();
}
}
谢谢。
This is a logging function which logs error stream from the execution of an external program. Everything works fine. But I do not want to generate the log file when there is no data in error stream. Currently it is creating zero size file. Please help.
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();
}
}
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
显而易见的事情是更改
为
The obvious thing to do is to change
to
只需推迟
FileOutputStream
和PrintWriter
的创建,直到您需要它:就我个人而言,我不是
PrintWriter
的忠实粉丝 - 事实上,它只是吞掉了所有与我有关的例外情况。我还使用OutputStreamWriter
以便您可以显式指定编码。无论如何,这与这里真正的问题无关。Simply defer the creating of the
FileOutputStream
andPrintWriter
until you need it:Personally I'm not a big fan of
PrintWriter
- the fact that it just swallows all exceptions concerns me. I'd also useOutputStreamWriter
so that you can explicitly specify the encoding. Anyway, that's aside from the real question here.