CSV数据到2D数组Java [英] CSV data to 2d array java

查看:64
本文介绍了CSV数据到2D数组Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能会以错误的方式进行处理,但是我的问题是,我将如何为fxRates填充数组?

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

这是我在CSV文件中拥有的信息,我当时正在考虑使用扫描仪类读取它.像

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)

推荐答案

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

这篇关于CSV数据到2D数组Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆