0

I have a .txt file and wish to read it in and store its content as an array list. Data in .txt file is like this :

1984      1   0.20  25.10   4.40  11.20   0.60   4.80   0.10   0.00   5.90  22.50   5.90  12.70   6.00   3.80   0.60  10.70   4.20   0.00   0.00   0.00   7.90   4.00  23.70   3.20   5.80   3.00   0.60   6.00   1.70   7.50   1.20

All in one line, 1984 for year, 1 for months, other values for respective days of months. I wish to store each line (ideally, each variable) in a different slot so its easily accessible by index.

I have written this code in order to read in the file and store the variables in an array list as I am unsure of the size of the array needed.

import java.io.*;
import java.util.*;

public class reader {
    public static void main(String[] args) {
        try {
            BufferedReader reader = new BufferedReader(new FileReader(
                    "2RainfallDataLanc.txt"));
            String line = null;
            ArrayList<String[]> rows = new ArrayList<String[]>();
            while ((line = reader.readLine()) != null) {
                String[] row = line.split("/t");
                rows.add(row);
            }
            System.out.println(rows.toString());
        } catch (IOException e) {
        }
    }
}

I receive an error message. Could someone tell me whats wrong with my code please?

4

1 回答 1

1

尝试使用

for (String[] row : rows) {
    System.out.println(Arrays.toString(row));
}

要查看输出。数组上的 ToString 不会产生任何有用的信息

假设您的数据点由空格分隔,您可以尝试使用此行解析它们

String[] row = line.split("\\s+");

+ 表示它前面的符号出现 1 次或多次(\s 是空格的简写,请参阅Java 中的正则表达式

于 2012-05-21T18:31:21.720 回答