2014-05-20 35 views
-3

我正尝试读取Java中的文件,并且出现错误。有没有人知道这个问题的解决办法?尝试读取文件时出错

我的代码:

import java.io.*; 
public class datafile{ static void readFile(){ 
    try { 
     BufferedReader bReader = new BufferedReader(new FileReader("itemslist.dat")); 
     String row; 
     String column1; 
     String column2; 
     String column3; 
     while((row = bReader.readLine()) != null){ 
      String[] itemWord = row.split("\t"); 
      column1 = itemWord[0]; 
      column2 = itemWord[1]; 
      column3 = itemWord[2]; 
     } 
    } catch (FileNotFoundException e) { 
     System.out.println("File not read properly"); 
     } 
} 
}  

我试图读取该文件的格式为:

食品熟400

其中空间是TABS。

这是我收到错误消息:

Exception in thread "AWT-EventQueue-0" java.lang.Error: Unresolved compilation problem: Unhandled exception type IOException 
at datafile.readFile(datafile.java:12) 

感谢您可以提供任何帮助!

+3

我建议你去一个基本的Java教程,了解异常。 – schmop

+1

你没有处理IOException。为什么你不读你的错误日志? – PKlumpp

回答

0

添加此

catch (FileNotFoundException e) { 
    System.out.println("File not read properly"); 
}catch(IOException e){ 
    System.out.println("input output problem"); 
} 

目前,你的代码只处理FileNotFoundException,代码可以抛出IOException,你需要处理

3

像错误说,你需要捕捉的IOException了。

由于FileNotFoundExceptionIOException的子类,因此除非要显示其他错误消息,否则不需要明确地捕获FileNotFoundException。它更改为:

catch (IOException e) { 
    System.out.println("File not read properly"); 
    e.printStackTrace(); 
} 

在Java 7,能够捕捉多个异常在单个catch块如下图所示,但没有必要在这种情况下,因为是FileNotFoundExceptionIOException一个子类。

catch (FileNotFoundException | IOException e) { 
    e.printStackTrace(); 
} 
+0

有需要multicatch,'FileNotFoundException'扩展'IOException' –

+0

true,你可以只捕获IOException。 – dogbane

相关问题