提问人:JavaNewbie_M107 提问时间:1/4/2013 更新时间:11/18/2015 访问量:21148
关闭链接到 System.in 的扫描仪
Close a Scanner linked to System.in
问:
我有一个链接到.现在,在使用 之后,我应该关闭它,因为让它保持打开状态是不好的编码实践。但是,如果我关闭 ,我也会关闭!谁能告诉我如何在不关闭的情况下关闭(如果有办法)。Scanner
System.in
Scanner
Scanner
System.in
Scanner
System.in
答:
最简单的方法是,如果您不想关闭底层流,请不要关闭 Scanner。
理想情况下,您应该只创建一个扫描仪,并在程序的整个生命周期内使用。无论如何,您似乎没有充分的理由关闭它。
评论
CloseShieldInputStream
一种选择是将流包装在防止其关闭的 a 中。然后,您的读者将使用 而不是原始流。System.in
CloseShieldInputStream
CloseShieldInputStream
System.in
下面是该类的 API:http://commons.apache.org/io/apidocs/org/apache/commons/io/input/CloseShieldInputStream.html
评论
与其添加盾牌类和类似的东西,不如放一个漂亮的评论和一个
@SuppressWarnings("resource")
这已经足够好了。而且我似乎没有看到这种方法有很多缺点。不要忘记评论。
评论
IOException: Stream closed
System.in
根据 InputSteam 的 API “InputStream 的 close 方法不做任何事情”,因此由于 System.in 是 InputStream 的实例,因此您无需担心 close() 被调用。
评论
Scanner
System.in
nextLine()
NoSuchElementException
close()
InputStream
InputStream
是一个抽象类。当子类表示使用后需要关闭的资源(例如 stdin)时,它们可以而且应该“做某事”。当然,这可以在 中更清楚,但你的结论是不正确的。InputStream.close()
I have vague memories of strange, undiagnosable problems long ago with using the same of twice, so this is what I use (even though you should probably just use one scanner for the duration of the program):Scanner
System.in
static String input() {
try {
return new Scanner(System.in).nextLine();
} catch (NoSuchElementException e) {
throw e;
}
}
For some reason this works without warnings, whereas if I don't do the catch-throw, Eclipse will complain .Resource leak: '<unassigned Closeable value>' is never closed
评论
System.in
InputStream
AutoClosable