wiryadev
wiryadev

Reputation: 1501

Import Data as Array from TXT File in Java

I want to import a data like this from .txt file using Java. Data in TXT

I want to import this as an Array. The class of data is like this:

class SolidStateDrive {
    String brand;
    String model;
    int capacityInGB;
}

So if the array from txt file is hardcoded, that would be like this:

ssd[0].brand = Samsung;
ssd[1].brand = Adata;

ssd[0].model = Evo970;
ssd[1].model = SU650;

ssd[0].capacityInGB = 512;
ssd[1].capacityInGB 240;

The problem is, when i try to read the .txt file, it only can store 1 data from first line. If more than one, it will give error ArrayOutOfBound Exception.

Im using while loop so that as long as the nextLine is not null, it will loop. This is my code:

int n = 0;
    SolidStateDrive[] ssd = new SolidStateDrive[n+1];
    
        try  {
            BufferedReader br = new BufferedReader(new FileReader("SSD.txt"));
            String line = null;
            while((line = br.readLine()) != null) {
                    String tmp[] = line.split("\t");
                    ssd[n] = new SolidStateDrive();
                    ssd[n].brand = tmp[0];
                    ssd[n].model = tmp[1];
                    ssd[n].capacityInGB = Integer.parseInt(tmp[2]);
                n++;
            }
            
            br.close();
        } catch(IOException ex) {
            ex.printStackTrace();
        }

Update : i already tried this but doesnt work either

SolidStateDrive[] ssd = new SolidStateDrive[2];

For complete code in that file : pastebin

Upvotes: 1

Views: 281

Answers (2)

Thirumal
Thirumal

Reputation: 9686

The problem is in splitting line String tmp[] = line.split("\t");.

Take line one from txt ssd[0].brand = Samsung; output of split is same as input ssd[0].brand = Samsung;.

while ((line = br.readLine()) != null) {
    String tmp[] = line.split("\t");
    ssd[n] = new SolidStateDrive();
    ssd[n].brand = tmp[0];
    ssd[n].model = tmp[1];
    ssd[n].capacityInGB = Integer.parseInt(tmp[2]);
    n++;
}

So the tmp[] will contain only tmp[0] = ssd[0].brand = Samsung;. When you try to access tmp[1] you will get

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1.

The solution to your problem,

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class ReadData {

    public static void main(String[] str) {
        readData();
    }

    public static void readData() {
        List<SolidStateDrive> ssd = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new FileReader("SSD.txt"))) {
            ssd = br.lines().map(s-> {
                String[] tmp = s.split("\\s+");
                return new SolidStateDrive(tmp[0], tmp[1], Integer.parseInt(tmp[2]));
            }).collect(Collectors.toList());
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        ssd.stream().forEach(System.out::println);
    }

}

class SolidStateDrive {
    
    String brand;
    String model;
    int capacityInGB;

    public SolidStateDrive(String brand, String model, int capacityInGB) {
        super();
        this.brand = brand;
        this.model = model;
        this.capacityInGB = capacityInGB;
    }

    @Override
    public String toString() {
        return "SolidStateDrive [brand=" + brand + ", model=" + model + ", capacityInGB=" + capacityInGB + "]";
    }
}

Upvotes: 1

Charlie Armstrong
Charlie Armstrong

Reputation: 2342

The ArrayOutOfBounds exception occurs in the code you posted in pastebin; you have a for loop that loops n+1 times, which will always be 1 more than the number of SSDs in the array. This is the offending for loop:

for (int j=0; j<=n; j++) {
    System.out.println(j+ "\t" +ssd[j].brand+ "\t" +ssd[j].model+ "\t" +ssd[j].capacityInGB);
}

To fix it, just change the <= to <, so the loop goes up to, but not including, n, since you started it at 0, not 1. It should look like this:

for (int j = 0; j < n; j++) {
    System.out.println(j + "\t" + ssd[j].brand + "\t" + ssd[j].model + "\t" + ssd[j].capacityInGB);
}

Upvotes: 1

Related Questions