java - Scanner(new File) 和 Scanner(new FileInputStream) 有什么区别?

标签 java file java.util.scanner

我观察到,Scanner 在用于文件读取时可以同时使用两个参数:FileFileInputStream

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/

相关文章:

javascript - 如何在 Android Studio 的 WebView 中自动填充网站字段/表单?

java - 在 Android 中引用文件时遇到问题

java - 如何通过输入用户输入使用java构建二维数组?

java - 将文本文件中的唯一单词添加到 ArrayList 的程序

java - 按降序对数组进行排序?

java - 限制需要反序列化的json字段为java对象的字段

Java Timer 不等待前一个 TimerTask 在新的 TimerTask 开始之前完成

c - fscanf (fi ,"%d %d", &used,&quota)==2 中等于 2 意味着什么?

objective-c - 如何将 NSString 中的路径转换为 ​​CFURLRef 和 FSRef*

java - 如果我正在扫描输入,我如何接受单个字符作为输入?