什么是Scanner(新文件)和Scanner(新FileInputStream)之间的区别?

use*_*078 2 java file java.util.scanner

我观察到,Scanner当用于文件读取工作时,两个参数:FileFileInputStream.

Scanner scan = new Scanner(new File("myfile.txt")); 
Run Code Online (Sandbox Code Playgroud)

Scanner scan = new Scanner(new FileInputStream("myfile.txt"));
Run Code Online (Sandbox Code Playgroud)

但是,我不知道这两个定义之间的区别.是否有任何与性能相关的差异?哪一个更喜欢?

有人请解释一下.谢谢.

Lui*_*oza 5

来自Scanner(File file)源代码:

public Scanner(File source) 
    throws FileNotFoundException
{
    this((ReadableByteChannel)(new FileInputStream(source).getChannel())); 
}
Run Code Online (Sandbox Code Playgroud)

框架将FileInputStream基于File实例创建.

在跟踪每个路径的源之后,它将调用此构造函数:

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());
}
Run Code Online (Sandbox Code Playgroud)

在性能方面,您不应该意识到这一点,因为JIT将在执行时为您提高性能.只有当您通过使用分析器发现线路成为瓶颈时,性能才有意义.