如果这是一个愚蠢的问题,请提前道歉,但我已经创建了一个窗口,其中有一个菜单栏和两个menuitems....when,单击“打开”,我想使用JFileChooser从我的计算机中选择一个文件,但是在我的扫描仪输入中没有找到一个未处理的异常类型文件。
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("text files", "txt");
chooser.setFileFilter(filter);
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
//get the selected file
java.io.File file = chooser.getSelectedFile();
//create scanner for the file
Scanner input = new Scanner(file);
//read text from file
while (input.hasNext()) {
System.out.println(input.nextLine());
}
//close the file
input.close();
} else {
System.out.println("No file selected");
}
}我知道我应该输入抛出异常,但是我的任何方法都不会使用it....My主方法抛出一个IOException。提前感谢
发布于 2014-04-04 21:00:28
如果不想抛出异常,则需要将生成异常的代码包围在try-catch块中,并在本地处理异常,如下所示:
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
//get the selected file
java.io.File file = chooser.getSelectedFile();
try {
//create scanner for the file
Scanner input = new Scanner(file);
//read text from file
while (input.hasNext()) {
System.out.println(input.nextLine());
}
//close the file
input.close();
} catch (FileNotFoundException fnfe) {
// handle exception here, e.g. error message to the user
}
} else {
System.out.println("No file selected");
}https://stackoverflow.com/questions/22872743
复制相似问题