CSV data to 2d array java

2019-07-30 15:28发布

Im probably going around this the wrong way, but My question is, how would I go about filling the array for fxRates?

CAD,EUR,GBP,USD
1.0,0.624514066,0.588714763,0.810307
1.601244959,1.0,0.942676548,1.2975
1.698615463,1.060809248,1.0,1.3764
1.234100162,0.772200772,.726532984,1.0

This is the information i have in the CSV file, I was thinking about using the scanner class to read it. Something like

private double[][] fxRates;
String delimiter = ","
Scanner sc = new Scanner(file);
    while (sc.hasNextLine()) {
        String line = sc.nextLine();
        fxRates = line.split(delimiter)

标签: java file
5条回答
兄弟一词,经得起流年.
2楼-- · 2019-07-30 16:04

Your way of solving this problem seems OK. But line.split(",") will return a 1D String array. You cannot assign it to fxRates. And also you should know the number of lines or rows in order to initialize fxRates at the beginning. Otherwise you should use a dynamic list structure like ArrayList.

Supposing you have 50 lines in your file, you can use something like:

private String[][] fxRates = String[50][];
String delimiter = ",";
Scanner sc = new Scanner(file);     
int index=0;

while (sc.hasNextLine()) 
{
    String line = sc.nextLine();
    fxRates[index++] = line.split(delimiter)
}

And note that I've declared fxRates as a 2D String array, if you need double values you should do some conversion in place or later on.

查看更多
我想做一个坏孩纸
3楼-- · 2019-07-30 16:10

I wouldn't recommend you to parse CSVs in such a way, because Scanner is too low-level and raw solution for this. In comparison, DOM/SAX parsers are better to parse XML rather than regular expressions parsing or whatever that does not consider the document structure. There are CSV parsers that feature good APIs and suggest configuration options during a reader initialization. Just take a look at easy to use CsvReader. Here is a code sample using it:

package q12967756;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collection;

import static java.lang.Double.parseDouble;
import static java.lang.System.out;

import com.csvreader.CsvReader;

public final class Main {

    private Main() {
    }

    private static final String MOCK =
            "CAD,EUR,GBP,USD\n" +
            "1.0,0.624514066,0.588714763,0.810307\n" +
            "1.601244959,1.0,0.942676548,1.2975\n" +
            "1.698615463,1.060809248,1.0,1.3764\n" +
            "1.234100162,0.772200772,.726532984,1.0\n";

    private static final char SEPARATOR = ',';

    public static void main(String[] args) throws IOException {
        // final FileReader contentReader = new FileReader("yourfile.csv");
        final StringReader contentReader = new StringReader(MOCK);
        final CsvReader csv = new CsvReader(contentReader, SEPARATOR);
        csv.readHeaders(); // to skip `CAD,EUR,GBP,USD`
        final Collection<double[]> temp = new ArrayList<double[]>();
        while ( csv.readRecord() ) {
            temp.add(parseRawValues(csv.getValues()));
        }
        final double[][] array2d = temp.toArray(new double[temp.size()][]);
        out.println(array2d[3][1]);
    }

    private static double[] parseRawValues(String[] rawValues) {
        final int length = rawValues.length;
        final double[] values = new double[length];
        for ( int i = 0; i < length; i++ ) {
            values[i] = parseDouble(rawValues[i]);
        }
        return values;
    }

}
查看更多
来,给爷笑一个
4楼-- · 2019-07-30 16:21

Another example;

        Double[][] fxRates = new Double[4][];
        String delimiter = ",";
        //file code goes here
        Scanner sc = new Scanner(file);
        // Read File Line By Line
        int auxI = 0;
        // Read File Line By Line
        for (int auxI =0; sc.hasNextLine(); auxI++) {
            String line = sc.nextLine();
            System.out.println(line);
            String[] fxRatesAsString = line.split(delimiter);
            Double[] fxRatesAsDouble = new Double[fxRatesAsString.length];
            for (int i = 0; i < fxRatesAsString.length; i++) {
                fxRatesAsDouble[i] = Double.parseDouble(fxRatesAsString[i]);
                }
            fxRates[auxI] = fxRatesAsDouble;
        }
        //to double check it
        for (int y =0; y<fxRates.length; y++){              
            for (int x =0; x<fxRates.length; x++){
                System.out.print(fxRates[y][x] +" ");
            }
            System.out.println("");
        }
查看更多
我命由我不由天
5楼-- · 2019-07-30 16:26
import java.nio.charset.Charset;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.io.IOException;

public class CSVReader{

    private String readFile(String path, Charset encoding) throws IOException
    {
        //Read in all bytes from a file at the specified path into a byte array
        //This method will fail if there is no file to read at the specified path
        byte[] encoded = Files.readAllBytes(Paths.get(path));
        //Convert the array of bytes into a string.
        return new String(encoded, encoding);
    }

    public String readFile(String path)
    {
        try {
            //Read the contents of the file at the specified path into one long String
            String content = readFile(path, Charset.defaultCharset());

            //Display the string.  Feel free to comment this line out.
            System.out.println("File contents:\n"+content+"\n\n");

            //Return the string to caller
            return content;

        }catch (IOException e){
            //This code will only execute if we could not open a file

            //Display the error message
            System.out.println("Cannot read file "+path);
            System.out.println("Make sure the file exists and the path is correct");

            //Exit the program
            System.exit(1);
        }`enter code here`
        return null;
    }
}
查看更多
Juvenile、少年°
6楼-- · 2019-07-30 16:26

The result of a split operation is a String array, not an array of double. So one step is missing: converting the Strings to doubles:

private double[][] fxRates = new double[maxLines][4];
String delimiter = ","
int line = 0;
Scanner sc = new Scanner(file);
    while (sc.hasNextLine()) {
        String line = sc.nextLine();
        String[] fxRatesAsString = line.split(delimiter);
        for (int i = 0; i < fxRatesAsString.length; i++) {
            fxRates[line][i] = Double.parseDouble(fxRatesAsString[i]);
        }
查看更多
登录 后发表回答