【发布时间】:2023-03-12 03:14:02
【问题描述】:
我一生都无法理解为什么 bufferedreader 没有读取我文件中的下一行。它一直返回一个空字符串。我以正确的格式将阅读器置于 while 循环中。我的文本文件不包含任何特殊字符。它只包含数字和一些由空格分隔的字符串。没看懂。
//Read from file method
public void readFile(File x) throws IOException{
File rFile = x;
String fileLine;
Transaction holder;
int Type;
//This will destroy the current account to add in the new one
//Main.$acct.destroyTrans();
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(rFile);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
//Gathering initial information about account
Main.$acct.setName(bufferedReader.readLine());
Main.$acct.setBalance(Double.parseDouble(bufferedReader.readLine()));
Main.$acct.setTransCount(Integer.parseInt(bufferedReader.readLine()));
Main.$acct.setSC(Double.parseDouble(bufferedReader.readLine()));
//Adding the objects
while((fileLine = bufferedReader.readLine()) != null) {
//Tokenize the String to extract information
StringTokenizer st = new StringTokenizer(fileLine," ");
//Go through each token and put it into an arrayList
ArrayList<String> list = new ArrayList();
while(st.hasMoreTokens()) {
list.add(st.nextToken());
}
//Grab each piece of data
Type = Integer.parseInt(list.get(0));
//Route the proper objects to their proper places
switch(Type){
case 1:
{
holder = new Check(Integer.parseInt(list.get(1)), Type, Double.parseDouble(list.get(3)), Integer.parseInt(list.get(2)));
Main.$acct.addNewTrans(holder);
break;
}
case 2:
{
holder = new Deposit(Integer.parseInt(list.get(1)), Type, Double.parseDouble(list.get(5)), Double.parseDouble(list.get(3)),
Double.parseDouble(list.get(4)));
Main.$acct.addNewTrans(holder);
break;
}
case 3:
{
holder = new Transaction(Integer.parseInt(list.get(1)), Type, Double.parseDouble(list.get(4)));
Main.$acct.addNewTrans(holder);
break;
}
default:
{}
}
//End of switch
}
//End of while loop
bufferedReader.close();
}
//End of Try
//Exception handling portion
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
rFile.getName() + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ rFile.getName() + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
示例文件:
比利
500
4
5
1 0 1 100
3 1 伺服。钟。 0.15
2 2 存款 100 100 200
【问题讨论】:
-
分享您的文件样本。
-
不要依赖
FileReader的默认编码,这是一个等着咬你的bug。 -
请发minimal reproducible example !!!这一堆代码(格式非常糟糕)太多了,无法分析。
-
您需要准确地告诉我们您的错误在哪里,因为我运行了示例文件,它似乎工作得很好。
标签: java file bufferedreader