简体   繁体   English

关闭链接到 System.in 的扫描仪

[英]Close a Scanner linked to System.in

I have a Scanner linked to System.in .我有一个链接到System.inScanner Now, after using the Scanner , I should close it, as it is bad coding practice to leave it open.现在,在使用Scanner ,我应该关闭它,因为让它保持打开状态是不好的编码习惯。 But, if I close the Scanner , I will also be closing System.in !但是,如果我关闭Scanner ,我也会关闭System.in Can anyone tell me how I can close the Scanner without closing System.in (if there is any way).谁能告诉我如何在不关闭System.in情况下关闭Scanner (如果有任何办法)。

The simplest thing is to not close Scanner if you don't want to close the underlying stream.如果您不想关闭底层流,最简单的事情就是不要关闭 Scanner。

Ideally you should create just one Scanner which you use for the life of the program.理想情况下,您应该只创建一个在程序生命周期中使用的扫描仪。 In any case, it appears you don't have a good reason to close it.无论如何,您似乎没有充分的理由关闭它。

One option is to wrap your System.in stream in a CloseShieldInputStream that prevents it from being closed.一种选择是将System.in流包装在CloseShieldInputStream ,以防止它被关闭。 Your reader would then use the CloseShieldInputStream rather than the raw System.in stream.然后,您的读者将使用CloseShieldInputStream而不是原始System.in流。

Here is the API for the class: http://commons.apache.org/io/apidocs/org/apache/commons/io/input/CloseShieldInputStream.html这是该类的 API: http : //commons.apache.org/io/apidocs/org/apache/commons/io/input/CloseShieldInputStream.html

Instead of adding shield classes and stuff like that, just put a nice comment and a而不是添加屏蔽类和类似的东西,只需添加一个很好的评论和

        @SuppressWarnings("resource")

That's good enough.这已经足够了。 And I don't seem to see a lot of drawbacks to this approach.而且我似乎没有看到这种方法有很多缺点。 Don't forget the comment.不要忘记评论。

I have vague memories of strange, undiagnosable problems long ago with using the same Scanner of System.in twice, so this is what I use (even though you should probably just use one scanner for the duration of the program):很久以前,我对使用System.in的同一个Scanner两次有一些奇怪的、无法诊断的问题的模糊记忆,所以这就是我使用的(即使你可能应该在程序运行期间只使用一个扫描仪):

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 .出于某种原因,这可以在没有警告的情况下工作,而如果我不进行 catch-throw,Eclipse 会抱怨Resource leak: '<unassigned Closeable value>' is never closed

根据InputSteamAPI “InputStream 的 close 方法什么都不做。”,因此由于 System.in 是 InputStream 的实例,因此您无需担心 close() 会被调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM