读取文件时发生java NumberFormatException错误
当我试图从文本文件中读取一些数据并将其转换为整数时,我遇到了一个NumberFormatException
错误。根据我看到的其他人所说的,当使用pasreInt()
将空字符串转换为整数时,会导致此错误。但我已经能够将文件中的字符串“1”打印到输出中。有人知道为什么我会出现这个错误,即使字符串似乎不是空的吗?这是我的密码:
try {
//Retrieve Info
FileReader fr = new FileReader("BankInfo.txt");
BufferedReader br = new BufferedReader(fr);
//Skip specified number of lines
for(int i=0; i<line; i++) {
br.readLine();
}
//Print the string to output
String holderStr = br.readLine();
System.out.println(holderStr);
//The line creating the NumberFormatException
totalBalNum = (double)Integer.parseInt(holderStr);
br.close();
//Read Whole File
BufferedReader br2 = new BufferedReader(fr);
while((str = br.readLine()) != null) {
arrList.add(str);
}
br2.close();
} catch (IOException | NumberFormatException e) {
System.out.println("ERROR! Problem with FileReader. " + e);
}
我知道我的代码可能真的很邋遢,效率也很低。。。我有点像个傻瓜
# 1 楼答案
好的,我认为将字符串转换为整数,然后将其类型转换为double会导致错误。为什么不把字符串转换成double呢。 此外,阅读时必须修剪线条,以避免出现空格
# 2 楼答案
使用
replaceAll()
将除数字以外的所有内容转换为空字符例如
字符串
extra34345 dfdf
将转换为34345
字符串
ab34345ba
将转换为34345
字符串
\n34345\n
将转换为34345
代码