Search code examples
javaarrayssplitjava.util.scannerreadfile

Read & split multiple column text file into arrays


For a project I'm working on a fairly big animal dataset with up to 14 parameters of data. I was able to read it in and display it as strings using this:

public static void readIn(String file) throws IOException {

    Scanner scanner = new Scanner(new File(file));
    while (scanner.hasNext()) {
        String[] columns = scanner.nextLine().split("/t");
        String data = columns[columns.length-1];
        System.out.println(data);
    }
}

and displaying something like this:

04:00:01    0.11    0.04    -0.1    1047470 977.91  91.75
04:00:01    0.32    -0.03   -0.07   1047505 977.34  92.91
04:00:01    0.49    -0.03   -0.08   1047493 978.66  92.17

But I'm currently having trouble trying to split each column into separate arrays so that I can process the data (e.g. calculating means). Any idea of how I can do this? Any help would be much appreciated.

Edit: thanks, I've found out a solution that works and also lets me choose which channel it reads specifically. I've also decided to store the data as arrays within the class, here's what I have now:

public static void readChannel(String file, int channel) throws IOException 
{
    List<Double> dataArr = new ArrayList<>();
    Scanner scanner = new Scanner(new File(file));
    while (scanner.hasNext()) {
        String[] columns = scanner.nextLine().split("\t");

        for (int i = channel; i < columns.length; i+=(columns.length-channel)) {
            dataArr.add(Double.parseDouble(columns[i]));
            dataArr.toArray();
        }
    }
}

Solution

  • You can store all rows in an ArrayList and then create arrays for each column and store values in them. Sample code:

    Scanner scanner = new Scanner(new File(file));
    ArrayList<String> animalData = new ArrayList<String>();
    while (scanner.hasNext()) {
        String[] columns = scanner.nextLine().split("/t");
        String data = columns[columns.length-1];
        animalData.add(data);
        System.out.println(data);
    }
    
    int size = animalData.size();
    String[] arr1 = new String[size]; String[] arr2 = new String[size]; 
    String[] arr3 = new String[size]; String[] arr4 = new String[size];
    for(int i=0;i<size;i++)
    {
        String[] temp = animalData.get(i).split("\t");
        arr1[i] = temp[0];
        arr2[i] = temp[1];
        arr3[i] = temp[2];
        arr4[i] = temp[3];
    }