System.out关闭了吗?我可以重新打开吗? [英] System.out closed? Can I reopen it?

查看:983
本文介绍了System.out关闭了吗?我可以重新打开吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在帮朋友写一些Java代码,他们对Java知之甚少。所以我给他写了一些辅助函数来轻松完成他眼中有点古怪的事情。其中一个是函数,它将String写入 OutputStream 。看看:

I was helping a friend to write some Java code, who doesn't know a lot about Java. So I wrote him some helper functions to easily get things done that are a little quirky in his eyes. One of them is a function, that writes a String to an OutputStream. Have a look:

public void write(String txt, OutputStream out) {
    PrintWriter printer = new PrintWriter(out);
    printer.print(txt);
    printer.close();
}

现在,您可以通过不同的方式轻松地使用它来编写您想要的任何地方。例如,你可以这样做:

Now, you can use that easily in different ways to write wherever you want. For example you could do that:

(new StreamHelper()).write("Hello Test", System.out);

这样做后我发现 System.out.println()不再向shell写入任何内容。所以我认为也许 printer.close()自动关闭 System.out 我想知道如何重新激活它我可以在此功能再次完成后使用它。

Doing that I found out that afterwards System.out.println() doesn't write anything to the shell anymore. So I think that maybe printer.close() automatically also closed System.out and I wonder how to reactivate it that I can use it after this function is finished again.

我的假设是否正确? (我怎么能在没有问这里的情况下找到它?)

Is my assumption correct? (How could I have found out without asking here?)

我怎样才能继续使用 System.out 之后调用 write()函数?

How can I continue to use System.out after a call to the write() function?

是否有更好的方法来编写这样的辅助函数?

Are there better ways to write such a helper function?

推荐答案

OutputStream的总合约已关闭:


public void close()
throws IOException关闭此输出流并释放与此流关联的所有系统资源。一般合约
的关闭是它关闭输出流。封闭流不能
执行输出操作而无法重新打开

PrintStream 's


public void close()关闭流。这是通过刷新
流然后关闭基础输出流来完成的。

我能给你的建议是你不应该写不对称代码<​​/a>,也就是说,不要将代码创建的资源关闭委托给其他地方。

The only advice I can give you is that you should not write asymmetrical code, that is, don't delegate the closing of resources your code has created to somewhere else.

即使在你的情况下关闭包装流似乎也是明智的,事实是你不应该因为你正在关闭在其他地方开通的溪流。

Even if in your case it might seemed sensible to close the wrapper stream, the fact is that you should not because you are closing a stream opened somewhere else.

简而言之:

public void write(String txt, OutputStream out) {
    PrintWriter printer = new PrintWriter(out);
    printer.print(txt);
    printer.flush();
    //it is very unpolite to close someone else's streams!
    //printer.close();
}

哦,顺便说一句,您可能想要将函数名称更改为 print ,而不是

Oh, and by the way, you may want to change the function name to print, rather than write.

这篇关于System.out关闭了吗?我可以重新打开吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆