Raúl
Raúl

Reputation: 23

How do I input data from a CSV file into my code?

I have a CSV file that is like:

What I want is that using scanner, I will be able to choose one of the two orbits I have in the CSV file. Let's say for example, using scanner if I put 1 in the console, it chooses the row of the CSV file: LEO,7168000,0,90 and if I put 2 the line: MEO,20200000,0,54.

After that from the row chosen it saves each parameter in a variable skipping the name (LEO,MEO). For example if I choose LEO orbit, it saves the variables like:

So in the end I can use those parameters in my program. Thank you for your answers.

Upvotes: 2

Views: 88

Answers (1)

tuanngocptn
tuanngocptn

Reputation: 1471

Csv file is a plain text file and separates with , character for each cell and \n for each row.

The easy way, you only need using FileInputStream to read and split \n and , character for using.

File file = new File("file.csv");
FileInputStream fis = null;
String dataStr = "";
try {
    fis = new FileInputStream(file);
    int content;
    while ((content = fis.read()) != -1) {
        dataStr += (char) content;
    }
} catch (IOException e) {
    e.printStackTrace();
}
// convert to array rows string
String[] dataRows = dataStr.split("\n");

// loop rows to get cells string
for (int i = 0; i < dataRows.length; i++) {
    String[] dataCells = rowData[i].split(",");
    //do what ever you want with dataCells
}

Thanks for read.

Upvotes: 1

Related Questions