关闭链接到System.in的扫描程序 [英] Close a Scanner linked to System.in
问题描述
我有扫描程序
链接到 System.in
。现在,在使用 Scanner
之后,我应该关闭它,因为将它打开是不好的编码习惯。但是,如果我关闭扫描仪
,我也将关闭 System.in
!任何人都可以告诉我如何关闭扫描仪
而不关闭 System.in
(如果有任何方式)。
I have a Scanner
linked to System.in
. Now, after using the Scanner
, I should close it, as it is bad coding practice to leave it open. But, if I close the Scanner
, I will also be closing System.in
! Can anyone tell me how I can close the Scanner
without closing System.in
(if there is any way).
推荐答案
一个选项是将 System.in
流包装在 CloseShieldInputStream
阻止它被关闭。然后,您的读者将使用 CloseShieldInputStream
而不是原始 System.in
流。
One option is to wrap your System.in
stream in a CloseShieldInputStream
that prevents it from being closed. Your reader would then use the CloseShieldInputStream
rather than the raw System.in
stream.
以下是该类的API:
http://commons.apache.org/io/apidocs/org/apache/commons/io/input/CloseShieldInputStream.html
Here is the API for the class: http://commons.apache.org/io/apidocs/org/apache/commons/io/input/CloseShieldInputStream.html
这篇关于关闭链接到System.in的扫描程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!