Java 将 csv 文件读入数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40074840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
reading a csv file into a array
提问by mikeL
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.
我正在尝试将 csv 文件“read_ex.csv”读入一个数组。我在 web/stackoverflow 上无休止地搜索,以找到一种将文件读入数组的方法。我能做的最好的事情就是以流媒体方式读取它,但由于文件大小可变,我无法将其存储在数组中。我相信 ArrayList 是一种处理可变大小数组的方法,但我不知道如何使用它。本质上,我希望能够在 while 循环完成后访问字符串数组“值”。
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"));
}
}
采纳答案by Michael Lihs
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:
虽然使用@Minjun.Y 提到的 Apache CSV 库非常好,但我尝试提供一个更接近您的代码并且可能更容易让您遵循的解决方案:
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++;
}
}
}
Let's go through it step-by-step:
让我们一步一步来:
I added 3 more imports:
ArrayList
,Arrays
andList
- you will see very soon for what they are good. They are all taken from thejava.util
library, a standard library that is available with every JDK.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.
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 variablelines
that holds the results of our parsing. TheList<String>
syntax means, that we have a generic typeList
that has a type parameterString
- in other words: a list of strings. The wholeList<List<String>>
means we have a list of lists of strings, a 2-dimensional string array.With the
lines.add(Arrays.asList(values))
in yourwhile
loop, we can add the lines that you parsed to this 2-dimensional array.Arrays.asList(values)
transforms theString[]
array into aList
as we need it to be compatible to ourList<List<...>>
type. This allows your lines to have variable length.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.
我加了3个进口:
ArrayList
,Arrays
和List
-你会很快对他们有什么好见。它们都取自java.util
库,这是每个 JDK 都可用的标准库。Java 中的每个类名都以大写字母开头(按照惯例——它也会用小写字母构建,但你应该习惯这个惯例)——我在你的代码中“修复”了这个。
我添加了一个二维数组
List<List<String>> lines = new ArrayList<>()
。乍一看这可能有点令人困惑,但这意味着我们创建了一个lines
保存解析结果的变量。该List<String>
语法手段,我们有一个泛型类型List
,有一个类型参数String
-换句话说:字符串列表。这List<List<String>>
意味着我们有一个字符串列表列表,一个二维字符串数组。随着
lines.add(Arrays.asList(values))
在你的while
循环中,我们可以添加您解析这个二维数组中的行。Arrays.asList(values)
将String[]
数组转换为 a,List
因为我们需要它与我们的List<List<...>>
类型兼容。这允许您的线条具有可变长度。我添加的最后几行只是打印二维数组的内容,并且应该为您提供一个关于如何访问该数组中值的好例子。如果您需要有关此构造的进一步帮助,请查看foreach 循环文档。
Given this as an input file (read_ex.csv
):
将此作为输入文件 ( 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
The program will print the following output:
该程序将打印以下输出:
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
Hope this helps :)
希望这可以帮助 :)
回答by Minjun Yu
I am new to java and wold be open to any method that reads a csv into a file that a beginner could understand.
我是 Java 新手,并且愿意接受任何将 csv 读入初学者可以理解的文件的方法。
Here is an existing solution for you from Apache Commons, the Apache Commons CSVproject. See the Apache Commons CSV parser guide.
这是Apache Commons 中为您提供的现有解决方案,Apache Commons CSV项目。请参阅Apache Commons CSV 解析器指南。
It is very easy to use out of the box.
开箱即用非常容易。
Here is a basic worfklow:
这是一个基本的工作流程:
- Create a class that has the fields that "match" the columns of csvfile.
- Each row in your csv is an object of that class with properties corresponding to the fields in your csv. Use the library to get each field and store it in your object in a loop.
- In your loop, you will store the object with the fields/properties read from the csv in the ArrayList
- After the loop ends, your ArrayList will have elements that "matches" the rows in your csv file. You are free to access any of the rows/elements in the list.
- 创建一个具有“匹配” csv文件列的字段的类。
- csv 中的每一行都是该类的对象,其属性与 csv 中的字段相对应。使用库获取每个字段并将其存储在循环中的对象中。
- 在您的循环中,您将在 ArrayList 中存储具有从 csv 读取的字段/属性的对象
- 循环结束后,您的 ArrayList 将具有与 csv 文件中的行“匹配”的元素。您可以自由访问列表中的任何行/元素。
If you are not familiar with how List
and ArrayList
works in Java, please refer to pretty much any Java tutorials online including the Oracle Tutorial.
如果你不熟悉如何List
和ArrayList
在Java中的作品,请参阅几乎任何Java在线教程,包括甲骨文教程。
Search Stackoverflowfor hundreds of posts about using Commons CSV.
在 Stackoverflow 上搜索数百篇关于使用 Commons CSV 的帖子。