我观察到,Scanner
在用于文件读取时可以同时使用两个参数:File
和 FileInputStream
。
Scanner scan = new Scanner(new File("myfile.txt"));
和
Scanner scan = new Scanner(new FileInputStream("myfile.txt"));
但是,我不知道这两个定义之间的区别。 是否存在与性能相关的差异? 更喜欢哪一个?
谁来解释一下。谢谢。
最佳答案
来自扫描仪(文件文件)
源代码:
public Scanner(File source)
throws FileNotFoundException
{
this((ReadableByteChannel)(new FileInputStream(source).getChannel()));
}
框架将基于File
实例创建FileInputStream
。
跟踪每个路径的源代码后,它将调用此构造函数:
private Scanner(Readable source, Pattern pattern) {
if (source == null)
throw new NullPointerException("source");
if (pattern == null)
throw new NullPointerException("pattern");
this.source = source;
delimPattern = pattern;
buf = CharBuffer.allocate(BUFFER_SIZE);
buf.limit(0);
matcher = delimPattern.matcher(buf);
matcher.useTransparentBounds(true);
matcher.useAnchoringBounds(false);
useLocale(Locale.getDefault());
}
就性能而言,您不应该意识到这一点,因为 JIT 会为您提高执行时的性能。仅当您通过使用探查器发现某行成为瓶颈时,性能才重要。
关于java - Scanner(new File) 和 Scanner(new FileInputStream) 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23371068/