Java,使用文件

时间:2013-12-28 13:29:35

标签: java string file

我有一个文本文件

category1 1 10 101 1 good1
category6 2 11 105 2 good5
category1 5 13 103 3 good4
category3 6 14 102 4 good2
category5 3 12 107 2 good1

如何阅读第5列?我需要找到其中的元素总和,但我不知道如何阅读它。这就是我所做的:

    int sum = 0;
    BufferedReader br = new BufferedReader(new FileReader("/Data.txt"));
    String line = br.readLine();
    String[] columns = line.split(" ");
    String[] items = columns[4].split(" ");
    for(int i = 0; i<items.length; i++){
        sum = sum + Integer.parseInt(items[i]);
    }

但它不起作用

2 个答案:

答案 0 :(得分:6)

您只是阅读文件的第一行。使用:

int sum = 0;
BufferedReader br = new BufferedReader(new FileReader("/Data.txt"));
String line;
while ((line = br.readLine()) != null)
{
    String[] columns = line.split(" ");
    sum = sum + Integer.parseInt(columns[4]);        
}

答案 1 :(得分:1)

int sum = 0;
    BufferedReader br = new BufferedReader(new FileReader("/Data.txt"));
String line = "";
while((line=br.readLine())!=null){
String[] columns = line.split(" ");


    sum = sum + Integer.parseInt(columns[4]);
}