user1408525
user1408525

Reputation: 1

Reading and storing txt. file content in an array list

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?

Upvotes: 0

Views: 5071

Answers (1)

Joey
Joey

Reputation: 1349

Try using

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

To see the output. ToString on an array produces nothing useful

Assuming your data points are separated by whitespaces, you could try to parse them with this line

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

+ means 1 or more occurences of the symbol in front of it (\s is shorthand for white space, see Regular Expressions in Java)

Upvotes: 1

Related Questions