将 csv 文件读入数组 [英] reading a csv file into a array

查看:41
本文介绍了将 csv 文件读入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 csv 文件read_ex.csv"读入一个数组.我在 web/stackoverflow 上无休止地搜索,以找到一种将文件读入数组的方法.我能做的最好的事情是以流媒体方式读取它,但由于文件大小可变,我无法将其存储在数组中.我相信 ArrayList 是一种处理可变大小数组的方法,但我不知道如何使用它.本质上,我希望能够在 while 循环完成后访问字符串数组值".

I am trying to read the csv file, "read_ex.csv", into an array. I have searched endlessly on the web/stackoverflow to find a way to read the file into an array. The best i have been able to do is read it in a streaming fashion, but I cant store it in an array due the variable size of the file. I belive that ArrayList is a method to deal with variable size array, but I don't know how to work with it. Essentially I want to be able to access the String array "values" after the while loop finishes.

import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.File;

public class sortarray {
     public static void main (String []agrs){
         String fileName= "read_ex.csv";
         File file= new File(fileName);


         try{
             Scanner inputStream= new Scanner(file);
             while(inputStream.hasNext()){
             String data= inputStream.next();
             String[] values = data.split(",");
             System.out.println(values[1]);
             }
             inputStream.close();
          }catch (FileNotFoundException e) {
             e.printStackTrace();
     }
     //This prints out the working directory
     System.out.println("Present Project Directory : "+ System.getProperty("user.dir"));

    }           

}

推荐答案

虽然使用@Minjun.Y 提到的 Apache CSV 库非常好,但我尝试提供一个更接近您的代码并且可能更容易的解决方案你要关注:

Although using the Apache CSV library as mentioned by @Minjun.Y is perfectly fine, I try to provide a solution that is closer to your code and maybe easier for you to follow:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class CsvParser {

    public static void main(String[] args) {
        String fileName= "read_ex.csv";
        File file= new File(fileName);

        // this gives you a 2-dimensional array of strings
        List<List<String>> lines = new ArrayList<>();
        Scanner inputStream;

        try{
            inputStream = new Scanner(file);

            while(inputStream.hasNext()){
                String line= inputStream.next();
                String[] values = line.split(",");
                // this adds the currently parsed line to the 2-dimensional string array
                lines.add(Arrays.asList(values));
            }

            inputStream.close();
        }catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        // the following code lets you iterate through the 2-dimensional array
        int lineNo = 1;
        for(List<String> line: lines) {
            int columnNo = 1;
            for (String value: line) {
                System.out.println("Line " + lineNo + " Column " + columnNo + ": " + value);
                columnNo++;
            }
            lineNo++;
        }
    }

}

让我们一步一步来:

  1. 我又添加了 3 个导入:ArrayListArraysList - 您很快就会看到它们的优点.它们都取自 java.util 库,这是一个每个 JDK 都可用的标准库.

  1. I added 3 more imports: ArrayList, Arrays and List - you will see very soon for what they are good. They are all taken from the java.util library, a standard library that is available with every JDK.

Java 中的每个类名都以大写字母开头(按照惯例——它也会用小写字母构建,但你应该习惯这个惯例)——我在你的代码中修复"了这个.

Every class name in Java starts with a capital letter (by convention - it will build with a small letter as well, but you should get used to this convention) - I "fixed" this in your code.

我添加了一个二维数组List>行 = 新的 ArrayList<>().乍一看这可能有点令人困惑,但这意味着我们创建了一个变量 lines 来保存我们的解析结果.List 语法意味着,我们有一个 generic type List 具有类型参数 String - 换句话说:字符串列表.整个List>意味着我们有一个字符串列表的列表,一个二维字符串数组.

I added a 2-dimensional array List<List<String>> lines = new ArrayList<>(). This might look a little confusing at first, but what it means is that we create a variable lines that holds the results of our parsing. The List<String> syntax means, that we have a generic type List that has a type parameter String - in other words: a list of strings. The whole List<List<String>> means we have a list of lists of strings, a 2-dimensional string array.

使用 lines.add(Arrays.asList(values)) 在您的 while 循环中,我们可以将您解析的行添加到这个 2-维数组.Arrays.asList(values)String[] 数组转换为 List,因为我们需要它与我们的 List< 兼容.列表<...>> 类型.这允许您的行具有可变长度.

With the lines.add(Arrays.asList(values)) in your while loop, we can add the lines that you parsed to this 2-dimensional array. Arrays.asList(values) transforms the String[] array into a List as we need it to be compatible to our List<List<...>> type. This allows your lines to have variable length.

我添加的最后几行只是打印二维数组的内容,并且应该为您提供一个关于如何访问该数组中的值的好例子.如果您需要有关此构造的进一步帮助,请查看 foreach 循环文档.

The last lines I added simply print the content of 2-dimensional array and should give you a good example for how to access the values in this array. If you need further help for this construct, check the foreach loop documentation.

将其作为输入文件 (read_ex.csv):

Given this as an input file (read_ex.csv):

value_1-1,value_1-2,value_1-3,value_1-4
value_2-1,value_2-2,value_2-3,value_2-4
value_3-1,value_3-2,value_3-3,value_3-4
value_4-1,value_4-2,value_4-3,value_4-4
value_5-1,value_5-2,value_5-3,value_5-4

程序将打印以下输出:

Line 1 Column 1: value_1-1
Line 1 Column 2: value_1-2
Line 1 Column 3: value_1-3
Line 1 Column 4: value_1-4
Line 2 Column 1: value_2-1
Line 2 Column 2: value_2-2
Line 2 Column 3: value_2-3
Line 2 Column 4: value_2-4
Line 3 Column 1: value_3-1
Line 3 Column 2: value_3-2
Line 3 Column 3: value_3-3
Line 3 Column 4: value_3-4
Line 4 Column 1: value_4-1
Line 4 Column 2: value_4-2
Line 4 Column 3: value_4-3
Line 4 Column 4: value_4-4
Line 5 Column 1: value_5-1
Line 5 Column 2: value_5-2
Line 5 Column 3: value_5-3
Line 5 Column 4: value_5-4

希望这有帮助:)

这篇关于将 csv 文件读入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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