我寫過一個應該使用BufferedReader
和FileReader
類讀取外部文件的程序。它識別文件併成功構建,但不會打印出應該執行的文本文件的內容。下面是代碼:使用BufferedReader和FileReader;文件正在讀取但不輸出其內容?
計劃
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class Lab9 {
public static void main(String[] args) {
BufferedReader reader = null;
String line;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a file name to read");
try {
reader = new BufferedReader(new FileReader("C:\\Users\\Lee\\Documents\\NetBeansProjects\\Lab9\\" + sc.next()));
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage() + "File was not found");
try {
while ((line = reader.readLine()) != null)
{
System.out.println(line);
}
} catch (IOException ex2) {
System.out.println(ex2.getMessage() + "File did not read correctly");
} finally {
System.exit(0);
}
}
}
}
應打印出這個樣子的該文件的內容:
文件內容
By what initials was Franklin Roosevelt better known?:FDR
Which number president was Franklin Roosevelt?:32
Which state was Franklin Roosevelt born in?:New York
In which year did Roosevelt become Governor of New York?:1929
What was the name of Franklin Roosevelt's wife?:Eleanor
How many children did Franklin Roosevelt have?:6
From which university did Franklin Roosevelt graduate with an A.B in history?:Harvard
What was the first name of Franklin Roosevelt's 5th cousin, who was also President?:Theodore
Which disease is believed to be the causes of Franklin Roosevelt's paralysis?:Polio
At what age did Franklin Roosevelt die?:63
實際輸出
Please enter a file name to read
Questions.txt
BUILD SUCCESSFUL (total time: 6 seconds)
任何幫助解決這個問題,非常感謝,謝謝。
這是否代碼編譯?你的第一個catch塊沒有關閉。或者是錯字? – developer
提示:在IDE中正確地格式化所有代碼,以便縮進將幫助您。然後看看你的'while'循環在哪裏。我建議刪除* all *你的try/catch語句,只聲明你的'main'方法可以拋出'IOException' ... –
我把一個括號放在錯誤的地方。通過縮進並正確格式化後,我發現錯誤,謝謝。 – Adam3920