简体   繁体   English

需要将 CSV 文件中的所有信息存储到 arrays

[英]Need to store all information from a CSV file to arrays

I am a beginner in java and i am trying to make a program that partly requires for all the info from the CSV files to be stored into arrays.我是 java 的初学者,我正在尝试制作一个程序,该程序部分需要将 CSV 文件中的所有信息存储到 arrays 中。 The CSV file only contains strings and has 23 rows and 3 columns. CSV 文件只包含字符串,有 23 行 3 列。 My problem is that i cannot find a way of storing everything since the array only stores the info from the last row, overwriting all the other rows.我的问题是我找不到存储所有内容的方法,因为数组只存储最后一行的信息,覆盖所有其他行。

''' '''

 public static void main(String[] args) throws FileNotFoundException{ 

    String[] StringPart=null;
    File csvfile = new File("FileExample");
    Scanner dodo = new Scanner(csvfile);

    while(dodo.hasNextLine()){
        String x = dodo.nextLine();
        StringPart= x.split(",");
        }

    System.out.println(StringPart[0]+StringPart[1]+StringPart[2]);

''' '''

You are doing wrong in this line of code StringPart= x.split(",");您在这行代码中做错了StringPart= x.split(","); . . Here you are assigning again and again new values to StringPart .在这里,您一次又一次地为StringPart分配新值。 Try to add values to the array of string StringPart .尝试将值添加到字符串StringPart的数组中。

Since you have columns and rows, a 2d array is an appropriate representation.由于您有列和行,因此二维数组是一种合适的表示形式。 2d arrays are an array of arrays. 2d arrays 是 arrays 的数组。 The outer array contains each row, the inner arrays contain each value.外部数组包含每一行,内部 arrays 包含每个值。

The Files and Paths utility classes are from java.nio.file.* .文件和路径实用程序类来自java.nio.file.*

public static void main(String[] args) throws Exception {
    // read file and store contents as String
    File file = new File("csv_example.txt");
    byte[] fileData = Files.readAllBytes(Paths.get(file.getAbsolutePath()));
    String fileContent = new String(fileData);

    String[][] values; // declare values
    String[] lines = fileContent.split("\n"); // split files in to lines
    values = new String[lines.length][]; // make values large enough to hold all lines

    // for each line, add its values to an array in the 2d values array
    for(int i = 0; i < lines.length; i++)
    {
      values[i] = lines[i].split(",");
    }
}

In java 8, we can easily achieve it在java 8中,我们可以轻松实现

BufferedReader br = new BufferedReader(new FileReader("test.csv"));
List<List<String>> dataList = br.lines()
    .filter(line -> line.length()>0) //ignoring empty lines
    .map(k -> Arrays.asList(k.split(",",-1))) // ,9346,Bharathi, -for this i should get [null,9346,Bharathi,null]
    .collect(Collectors.toCollection(LinkedList::new));

outer list will have rows and inner list will have corresponding column values外部列表将具有行,内部列表将具有相应的列值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM