簡體   English   中英

CSV數據到二維數組java

[英]CSV data to 2d array java

我可能以錯誤的方式解決這個問題,但我的問題是,我將如何為 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)

你解決這個問題的方法似乎沒問題。 但是line.split(",")將返回一個一維字符串數組。 您不能將其分配給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 字符串數組,如果您需要雙fxRates值,您應該就地或稍后進行一些轉換。

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

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

另一個例子;

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

我不建議你以這種方式解析 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;
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM