2017-08-27 85 views
1

我有一个打印机文件,打印文件的所有内容。我知道,先进的东西。 现在我可以通过在我的方法中声明扫描器对象调用文件,该文件是调用中的对象变量,从而使程序成功运行。使用扫描仪读取文件时,为什么扫描仪必须处于该方法中?

我的问题是,当我在我的构造函数中声明文件和扫描器时,它只是返回给我文件的名称。不知道我是否解释得好。

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的

回答

1

您的扫描仪获取文件名 - 而不是文件。

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

这应该会帮助您查看内容。

+0

感谢您的回答,在构造函数中声明它或在方法内部声明它是更好的做法吗? – ibrahim

+1

我会说方法 - 确保你看到你打开的资源,并在不使用时关闭它。 – Assafs