java - 使用扫描仪读取文件时,为什么扫描仪必须在方法中?

标签 java file stack java.util.scanner

我有一个打印机文件,可以打印文件的所有内容。我知道,先进的东西。 现在我可以通过在我的方法中声明扫描仪对象来调用文件(该文件是调用中的对象变量)来使程序成功运行。

我的问题是,当我在构造函数中声明文件和扫描仪时,它只返回文件名。不确定我是否解释得很好。

public class Printer {
private File file;
private Scanner reader;


public Printer(String fileName) {
    this.file = new File(fileName);
    this.reader = new Scanner(fileName);
}

public void printContents() throws FileNotFoundException {

    while (reader.hasNextLine()) {
        String line = reader.nextLine();
        System.out.println(line);
    }

    reader.close();
}

然后是我的主要内容

    public class Main {

public static void main(String[] args) throws Exception {
Printer printer = new Printer("src/textfile.txt");
printer.printContents();
}

}

这只是打印出 src/textfile.txt

最佳答案

您的扫描仪获取的是文件名,而不是文件本身。

public Printer(String fileName) {
    this.file = new File(fileName);
    this.reader = new Scanner(file); //note the change
}

这应该可以帮助您了解内容。

关于java - 使用扫描仪读取文件时,为什么扫描仪必须在方法中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45904388/

相关文章:

java - Android/Gradle/Unity - 在 AAR 插件中包含所有依赖项

java - OOP 票价计划

java - 相同对象的两个列表具有不同的哈希码

C++将数据从数据文件输入到结构变量中

.net - 如何使Stack.Pop线程安全

javascript - 全局变量值在 node.js 中的无限递归超过堆栈后神秘地重置

java - Spring 和@Value 注解

c - 在 BST 中如何将数组保留为值?

c - intel x86 - 为什么 -4(%ebp) 没有任何意义?

c++ - 将二维数组保存到文件 C++