我需要从.dat文件中读取文本,其内容如下:
4
Mary 13.99
Ruth 22.04
Anne 12.39
Talor 18.34
我使用了一个如下所示的缓冲读取器:
public class Tester{
public static void main(String [] args){
BufferedReader reader = null;
try {
File file = new File("C:\\Users\\hoguetm\\workspace\\practiceproblems\\beautiful.dat");
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
//System.out.println(line);
//split will go here
String[] str1Array = line.split(" ");
System.out.println(str1Array[0]);
//works
/*
for (String retval: line.split(" ")){
System.out.println(retval);
}
*/
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
我需要在除4之外的行末添加数字并打印出总和,但是当我将[0]更改为[1]时,它表示超出范围。请帮忙
如果您保证输入文件的格式与您发布的格式相同,则只需执行以下操作:
reader.readLine();
while ((line = reader.readLine()) != null) {
...
这将导致您的读者占用文件的第一行并完全忽略它。就是说,您发布的文件表明第一行指示随后的行数,这意味着您应该解析它并使用for
循环。例如:
int nLines = Integer.parseInt(reader.readLine());
for(int i = 0; i < nLines; i++)
{
line = reader.readLine();
...
}
不过,这完全基于您提供的小样本。有关dat文件规范的更多信息将很有用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句