读取Java中的CSV文件并将值存储在int数组

读取Java中的CSV文件并将值存储在int数组

本文介绍了读取Java中的CSV文件并将值存储在int数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下格式的字符串CSV文件:

I have a CSV file of strings in this format:

14/10/2011  422     391.6592    394.52324   0.039215686
13/10/2011  408.43  391.7612    395.0686031 0.039215686
12/10/2011  402.19  391.834     395.3478736 0.039215686

我要做的就是读取csv文件,然后将第3和第4列数据存储在整数数组中.

All I want to do is read in the csv file and then store the 3rd and 4th coloumns data in integer arrays.

这是我编写的代码:

    BufferedReader CSVFile =
            new BufferedReader(new FileReader("appleData.csv"));

    String dataRow = CSVFile.readLine();
    int count = 0;

    while (dataRow != null){
        String[] dataArray = dataRow.split(",");

        EMA[count] = dataArray[2];
        SMA[count] = dataArray[3];

        dataRow = CSVFile.readLine(); // Read next line of data.
    }
    // Close the file once all data has been read.
    CSVFile.close();

我想最后得到两个数组,EMA包含第3列的所有值,而SMA包含第4列的所有值.

I want to end up with two arrays, EMA which contains all the values from the 3rd coloumn and SMA which contains the values from the 4th coloumn.

我收到一个空指针异常.有人可以告诉我我犯了什么错误吗?

I am getting a null pointer exception. Can someone please tell me what mistake I am making?

推荐答案

您的文件似乎使用空格/制表符作为分隔符,但您使用逗号分隔.这对我来说毫无意义.

Your file appears to use whitespace/tab as a delimiter, but you're splitting at commas. That makes no sense to me.

您假定数据行具有一定的长度而不检查它.这对我来说毫无意义.

You assume that the data row has a certain length without checking it. That makes no sense to me.

此代码将向您展示如何做得更好:

This code will show you how to do it better:

package cruft;

import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * CsvParser
 * @author Michael
 * @link http://stackoverflow.com/questions/14114358/reading-csv-file-in-java-and-storing-the-values-in-an-int-array/14114365#14114365
 * @since 1/1/13 4:26 PM
 */
public class CsvParser {
    public static void main(String[] args) {
        try {
            FileReader fr = new FileReader((args.length > 0) ? args[0] : "resources/test.csv");
            Map<String, List<String>> values = parseCsv(fr, "\\s+", true);
            System.out.println(values);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Map<String, List<String>> parseCsv(Reader reader, String separator, boolean hasHeader) throws IOException {
        Map<String, List<String>> values = new LinkedHashMap<String, List<String>>();
        List<String> columnNames = new LinkedList<String>();
        BufferedReader br = null;
        br = new BufferedReader(reader);
        String line;
        int numLines = 0;
        while ((line = br.readLine()) != null) {
            if (StringUtils.isNotBlank(line)) {
                if (!line.startsWith("#")) {
                    String[] tokens = line.split(separator);
                    if (tokens != null) {
                        for (int i = 0; i < tokens.length; ++i) {
                            if (numLines == 0) {
                                columnNames.add(hasHeader ? tokens[i] : ("row_"+i));
                            } else {
                                List<String> column = values.get(columnNames.get(i));
                                if (column == null) {
                                    column = new LinkedList<String>();
                                }
                                column.add(tokens[i]);
                                values.put(columnNames.get(i), column);
                            }
                        }
                    }
                    ++numLines;
                }
            }
        }
        return values;
    }
}

这是我用来测试的输入文件:

Here's the input file I used to test it:

# This shows that comments, headers and blank lines work fine, too.
date        value1  value2      value3      value4
14/10/2011  422     391.6592    394.52324   0.039215686

13/10/2011  408.43  391.7612    395.0686031 0.039215686



12/10/2011  402.19  391.834     395.3478736 0.039215686

这是我得到的输出:

{date=[14/10/2011, 13/10/2011, 12/10/2011], value1=[422, 408.43, 402.19], value2=[391.6592, 391.7612, 391.834], value3=[394.52324, 395.0686031, 395.3478736], value4=[0.039215686, 0.039215686, 0.039215686]}

Process finished with exit code 0

这篇关于读取Java中的CSV文件并将值存储在int数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 01:43