2011-03-11 80 views
0

在我的程序中,我想从文本文件中读取。我的文件中的数据是由空格分隔的数字。我会在我的程序中将它们转换为整数。如果从文件读取的数据不是数字,我想捕获异常。我想知道文件的哪一行发生了错误(数据不是数字)。我知道我应该赶上NumberFormatException异常,但不知道如何找到异常行。 这里是一个代码位:如何知道IOexception发生在文件的哪一行

try 
{ 
    //...using Bufferreader ...some code here 
    while ((strLine = br.readLine()) != null) 
    { 
    String[] term = strLine.split(" "); 
    //for now i just work with the first element of the array 
    int num = Integer.parseInt(term[0]); 
    //....some code here 
    } 
    in.close(); 
} 
catch (NumberFormatException eg) 
{ 
    System.out.println("Error: there is a problem in line ..? "); 
} 

回答

0
int num = Integer.parseInt(term[0]); 

上面一行将抛出NumberFormatException的参数时不会号码。

4
int line = 0; 
try 
{ 
    //...using Bufferreader ...some code here 
    while ((strLine = br.readLine()) != null) 
    { 
    line ++; 
    String[] term = strLine.split(" "); 
    //for now i just work with the first element of the array 
    int num = Integer.parseInt(term[0]); 
    //....some code here 
    } 
    in.close(); 
} 
catch (NumberFormatException eg) 
{ 
    System.out.println("Error: there is a problem in line " + line); 
} 
相关问题