将2d数组写入csv文件

时间:2017-09-27 01:32:36

标签: java csv multidimensional-array

我有一个有2d数组的程序,我需要写一个csv文件,但我只需要编写一个数组索引。我使用.get(0).set(4,newAmount)在第一个索引中设置一个值,但如果有意义,我需要将索引的所有值都写入文件。

         fw = new FileWriter(FILE_NAME, true);
         bw = new BufferedWriter(fw);

        System.out.println("Enter the name of the person you want to change amount for");
       String changeName = FileUtility.getInput().nextLine();
       String newAmount;



        Scanner s = new Scanner(new File(FILE_NAME));
        String str = "";
        List<List<String>> list = new ArrayList<List<String>>();

        while (s.hasNext()) {
        list.add(Arrays.asList(s.nextLine().split(",")));
 }

 if (list.get(0).get(0).equalsIgnoreCase(changeName)) {
  System.out.println("Enter the new amount paid for the player");
  newAmount = FileUtility.getInput().nextLine();
  list.get(0).set(4, newAmount);
  //write to csv file here

1 个答案:

答案 0 :(得分:0)

将此代码放在代码的底部。

String csv = list.stream()
    .map(row -> row.stream()
      .map(col -> col.toString())
        .collect(Collectors.joining(", ")))
    .collect(Collectors.joining("\n"));
writer.write(csv);