我有一个打印机文件,可以打印文件的所有内容。我知道,先进的东西。 现在我可以通过在我的方法中声明扫描仪对象来调用文件(该文件是调用中的对象变量)来使程序成功运行。
我的问题是,当我在构造函数中声明文件和扫描仪时,它只返回文件名。不确定我是否解释得很好。
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/