Reputation: 165
I have a CSV file with different columns of data.
Example:
100, 0.1, 0.5
200, 0.1, 0.1
300, 0.2, 0.5
etc
I want to store the first column into an array, the second column into its own array and so on so that I can use them for math equations.
import.java.util.Scanner;
import java.io.File;
public class Example
{
public static void main(String[] args) throws Exception
{
Scanner s = new Scanner(new File("C://java//data.txt"));
}
}
I'm pretty lost up until this point.
Upvotes: 0
Views: 105
Reputation: 227
You can try this:
public class ReadCSV {
public static List<List<Double>> getDimensionList(String key) throws Exception
{
List<List<Double>> listOfDimension = new ArrayList<List<Double>>();
List<Double> dimensionList = null;
File file = null;
BufferedReader br = null;
try {
file = new File(key);
br = new BufferedReader(new FileReader(file));
String strLine = "";
StringTokenizer dimensionVal = null;
int lineNumber = 0, tokenNumber = 0;
while( (strLine = br.readLine()) != null)
{
dimensionVal = new StringTokenizer(strLine, ",");
dimensionList = new ArrayList<Double>();
while(dimensionVal.hasMoreTokens())
{
tokenNumber++;
dimensionList.add(Double.parseDouble(dimensionVal.nextToken()));
if(tokenNumber == 3)
{
Comparator<Double> comparator = Collections.reverseOrder();
Collections.sort(dimensionList,comparator);
}
}
listOfDimension.add(dimensionList);
tokenNumber = 0;
lineNumber++;
}
}catch (Exception e) {
throw new Exception();
}
finally
{
if(br != null)
br.close();
}
return listOfDimension;
}
public static void main(String[] args) throws Exception {
System.out.println(getDimensionList("dimension_details.csv"));
}
Upvotes: 1