CSV数据到2d数组java

时间:2012-10-19 05:11:56

标签: java file

我可能会以错误的方式解决这个问题,但我的问题是,我将如何为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

这是我在CSV文件中的信息,我正在考虑使用扫描仪类来读取它。像

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

5 个答案:

答案 0 :(得分:1)

你解决这个问题的方法似乎没问题。但line.split(",")将返回1D String数组。您无法将其分配给fxRates。此外,您应该知道行或行的数量,以便在开头初始化fxRates。否则,您应该使用动态列表结构,如ArrayList

假设您的文件中有50行,您可以使用以下内容:

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)
}

请注意,我已将fxRates声明为2D字符串数组,如果您需要双值,则应在适当位置或稍后进行转换。

答案 1 :(得分:1)

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;
    }
}

答案 2 :(得分:0)

split操作的结果是String数组,而不是double的数组。因此缺少一步:将字符串转换为双精度:

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]);
        }

答案 3 :(得分:0)

另一个例子;

        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("");
        }

答案 4 :(得分:0)

我不建议您以这种方式解析CSV,因为Scanner太低级且原始解决方案。相比之下,DOM / SAX解析器更好地解析XML而不是正则表达式解析或任何不考虑文档结构的解析器。有一些CSV解析器具有良好的API,并在阅读器初始化期间提供配置选项。只需看看易于使用的CsvReader。以下是使用它的代码示例:

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;
    }

}