需要将所有信息从CSV文件存储到数组

时间:2020-04-24 21:13:24

标签: java arrays string csv split

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

'''

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

由于具有列和行,因此2d数组是合适的表示形式。 2d数组是数组的数组。外层数组包含每一行,内层数组包含每个值。

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

答案 2 :(得分:0)

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

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

相关问题