【问题标题】:Writing a 2d array to a csv file将二维数组写入 csv 文件
【发布时间】:2018-03-08 08:47:36
【问题描述】:

我有一个具有二维数组的程序,我需要写入 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

【问题讨论】:

    标签: java csv multidimensional-array


    【解决方案1】:

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

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

    【讨论】:

    • 不起作用,它只是删除了文件中存在的所有内容
    • @RyanBlanchard 你的意思是扫描的文件有空值??
    猜你喜欢
    • 2021-01-09
    • 2021-09-05
    • 2014-09-13
    • 1970-01-01
    • 2011-08-12
    • 2016-09-27
    • 1970-01-01
    • 2020-05-01
    • 2015-05-16
    相关资源
    最近更新 更多