首页 > Java > java教程 > 我应该关闭链接到 System.in 的扫描程序吗?

我应该关闭链接到 System.in 的扫描程序吗?

Linda Hamilton
发布: 2024-12-20 18:27:20
原创
1068 人浏览过

Should I Close a Scanner Linked to System.in?

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

关闭链接到 System.in 的扫描仪可能会让人左右为难。虽然关闭开放资源是一种良好的编码习惯,但使用连接到 System.in 的扫描程序执行此操作也会关闭 System.in 本身。这就提出了一个问题:有没有办法在不影响 System.in 的情况下关闭扫描程序?

解决方案

最简单的解决方案是不要关闭扫描程序,如果您不打算关闭底层流。在大多数情况下,建议创建一个为整个程序提供服务的扫描程序。这样就无需重复创建和关闭它。

如果由于某种原因必须关闭 Scanner,一种选择是使用相同的底层流创建一个新的 Scanner 实例。这将两个实体分开,并允许您关闭扫描程序而不影响 System.in。

这是一个示例:

Scanner scanner = new Scanner(System.in);
// Use the scanner as needed...

// Create a new scanner with the same underlying stream.
Scanner newScanner = new Scanner(System.in);

// Close the first scanner.
scanner.close();

// Continue using the new scanner.
newScanner.nextInt();

// Close the second scanner.
newScanner.close();
登录后复制

此方法可确保 System.in 不受影响,同时允许您关闭原始 Scanner。

需要注意的是,创建多个 Scanner 实例可能会对性能产生影响。如果性能是一个问题,最好在程序的整个生命周期中使用单个扫描仪。

以上是我应该关闭链接到 System.in 的扫描程序吗?的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板