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的
感謝您的回答,在構造函數中聲明它或在方法內部聲明它是更好的做法嗎? – ibrahim
我會說方法 - 確保你看到你打開的資源,並在不使用時關閉它。 – Assafs