如果我关闭了底层可读文件,不关闭Java扫描程序是否安全? [英] Is it safe not to close a Java Scanner, provided I close the underlying readable?

查看:68
本文介绍了如果我关闭了底层可读文件,不关闭Java扫描程序是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个采用读取器的方法,并且想要使用类似扫描器"的读取器进行操作,则如下所示:

If I have a method that takes a reader and I want to operate on the reader with a Scanner like so:

Scanner scanner = new Scanner(reader);
while(scanner.hasNext()) {
    //blah blah blah
}

不关闭scanner是否安全?文档说它关闭了该扫描仪",然后讨论了关闭底层可读文件.假设我不想关闭可读性,而是希望调用者在准备好时关闭reader.是否可以安全地在此处关闭scanner?

Is it safe not to close scanner? Documentation says that it "closes this scanner" and then talks about closing the underlying readable. Suppose I don't want to close the readable and instead want the caller to close reader when ready. Is it safe not to close scanner here?

推荐答案

这取决于您要安全防范的内容.

It depends what you want to be safe against.

  • 如果您只是想确保关闭基础流,那么两种方法都可以.

  • If you are just trying to ensure that the underlying stream is closed, then either approach is fine.

如果您还希望将Scanner标记为已关闭(以便对该对象的所有后续操作将立即失败),则应调用Scanner.close().

If you also want the Scanner to be marked as closed (so that all subsequent operations on the object will fail immediately), then you should call Scanner.close().

这是一般原则;即它也适用于以一种或另一种方式在内存中进行缓冲的各种流.

This is a general principle; i.e. it also applies to various kinds of streams that do in-memory buffering, one way or another.

这篇关于如果我关闭了底层可读文件,不关闭Java扫描程序是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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