【发布时间】:2016-11-26 16:36:56
【问题描述】:
我编写了一个程序,它应该使用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 块没有在那里关闭。还是错字?
-
提示:在 IDE 中正确格式化所有代码,以便缩进对您有所帮助。然后看看你的
while循环在哪里。我建议删除 all 您的 try/catch 语句,并声明您的main方法可以抛出IOException... -
我将其中一个括号放在了错误的位置。经过缩进并正确格式化后,我发现了错误,谢谢。
标签: java bufferedreader filereader