【问题标题】:Need to store all information from a CSV file to arrays需要将 CSV 文件中的所有信息存储到数组中
【发布时间】:2020-08-08 13:36:56
【问题描述】:

我是 java 初学者,我正在尝试制作一个程序,该程序部分需要将 CSV 文件中的所有信息存储到数组中。 CSV 文件仅包含字符串,有 23 行和 3 列。我的问题是我找不到存储所有内容的方法,因为数组只存储最后一行的信息,覆盖所有其他行。

'''

 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]);

'''

【问题讨论】:

  • 使用List<String[]>List<String> 或二维String[][] 数组。

标签: java arrays string csv split


【解决方案1】:

您在这行代码StringPart= x.split(","); 中做错了。在这里,您一次又一次地为StringPart 分配新值。尝试将值添加到字符串数组StringPart

【讨论】:

  • 我已尝试多次将 Stringpart 存储到数组中,但始终失败或产生错误。我该怎么做?
【解决方案2】:

由于您有列和行,因此二维数组是一种合适的表示形式。二维数组是数组的数组。外部数组包含每一行,内部数组包含每个值。

文件和路径实用程序类来自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(",");
    }
}

【讨论】:

    【解决方案3】:

    在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));
    

    外部列表有行,内部列表有对应的列值

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-11
      • 1970-01-01
      • 2018-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多