You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java读取CSV到内存、删除末行后回写以解决新增玩家重复写入问题

问题根因
  • 原有代码每次运行都会直接以追加模式向CSV写入Jimmy的玩家记录,没有做重复校验,导致每执行一次程序就新增一条重复记录
  • readWrite2方法中冗余声明了FileWriter对象但未使用,属于无效代码
修复实现(按需求逻辑:全量读入内存→去重校验→全量回写)

核心修改addGamer方法逻辑:

  1. 先把CSV所有行读取到List<String>内存集合中
  2. 校验待新增的玩家是否已经存在,存在则不重复写入
  3. 确认需要新增时,将内存中所有记录+新记录一次性覆盖写入CSV文件,替代原有追加写入逻辑
完整修改后代码
package week3assignment;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class Jaret_Dalrymple_GamesReport {

    public static void main(String[] args) throws IOException {
        File gameScores = new File("C:\\Users\\jaret\\OneDrive\\Desktop\\GameScores.csv");
        readWrite(gameScores);
        addGamer(gameScores, "Jimmy", "189", "190", "197", "199", "198", "193", "199", "199", "188", "196");
        readWrite2(gameScores);
    }

    private static void readWrite(File gameScores) throws IOException {
        if (gameScores.exists()) {
            BufferedReader br = null;
            String line = "";
            String csvSplitBy = ",";
            int gamerCount = 0;
            int topScore = 0;
            String topScorer = "";
            br = new BufferedReader(new FileReader(gameScores));
            System.out.println("----------------------------------------------------------");
            System.out.println("-------------------------------------");
            System.out.println("Games Report");
            System.out.println("----------------------------------------------------------");
            System.out.println("-------------------------------------");
            System.out.println("Gamer   1   2   3   4   5   6   7");
            System.out.println("    8   9   10  Total");
            System.out.println("----------------------------------------------------------");
            System.out.println("-------------------------------------");

            while ((line = br.readLine()) != null) {
                if(line.trim().isEmpty()) continue; // 跳过空行
                String list[] = line.split(csvSplitBy);
                int sum = 0;

                for (int i = 1; i < list.length; i++) {
                    try {
                        Integer num = Integer.parseInt(list[i]);
                        sum += num;
                    } catch (NumberFormatException nfe) {
                        // 跳过非数字字段
                    }
                }
                // 打印逻辑保留原有格式
                System.out.print(list[0] + "\t" + list[1] + "\t" + list[2]
                        + "\t" + list[3]
                        + "\t" + list[4]
                        + "\t" + list[5]
                        + "\t" + list[6]
                        + "\t" + list[7]
                        + "\n\t" + list[8]
                        + "\t" + list[9]
                        + "\t" + list[10] + "\t");

                if (sum > topScore) {
                    topScore = sum;
                    topScorer = list[0];
                }

                System.out.println(sum);
                gamerCount++;
            }

            System.out.println("----------------------------------------------------------");
            System.out.println("-------------------------------------");
            System.out.println("# of Gamers:    " + gamerCount);
            System.out.println("Top Gamer:  " + topScorer);
            System.out.println("----------------------------------------------------------");
            System.out.println("-------------------------------------");
            br.close();
        }
    }

    // 重写后的新增玩家方法,避免重复写入
    private static void addGamer(File gameScores, String gamerName, String second, String third, String fourth,
                                 String fifth, String sixth, String seventh, String eighth, String ninth, String tenth, String eleventh)
            throws IOException {
        List<String> allLines = new ArrayList<>();
        boolean isGamerExist = false;
        // 第一步:全量读取CSV所有行到内存
        if (gameScores.exists()) {
            BufferedReader br = new BufferedReader(new FileReader(gameScores));
            String line;
            while ((line = br.readLine()) != null) {
                if(line.trim().isEmpty()) continue;
                allLines.add(line);
                // 校验玩家是否已存在,这里以第一个字段玩家名为判断依据
                if(line.split(",")[0].equals(gamerName)){
                    isGamerExist = true;
                }
            }
            br.close();
        }
        // 玩家已存在则直接返回不新增
        if(isGamerExist){
            System.out.println("玩家" + gamerName + "记录已存在,无需重复添加");
            return;
        }
        // 第二步:拼接新记录
        String newLine = gamerName + "," + second + "," + third + "," + fourth + "," + fifth + "," + sixth + "," +
                seventh + "," + eighth + "," + ninth + "," + tenth + "," + eleventh;
        allLines.add(newLine);
        // 第三步:全量回写覆盖CSV文件
        FileWriter fw = new FileWriter(gameScores);
        for (String line : allLines) {
            fw.write(line + "\n");
        }
        fw.close();
        System.out.println("玩家" + gamerName + "记录添加成功");
    }

    private static void readWrite2(File gameScores) throws IOException {
        if (gameScores.exists()) {
            BufferedReader br = null;
            String line = "";
            String csvSplitBy = ",";
            int gamerCount = 0;
            int topScore = 0;
            String topScorer = "";
            // 移除冗余的FileWriter声明
            br = new BufferedReader(new FileReader(gameScores));
            System.out.println("----------------------------------------------------------");
            System.out.println("-------------------------------------");
            System.out.println("Games Report");
            System.out.println("----------------------------------------------------------");
            System.out.println("-------------------------------------");
            System.out.println("Gamer   1   2   3   4   5   6   7");
            System.out.println("    8   9   10  Total");
            System.out.println("----------------------------------------------------------");
            System.out.println("-------------------------------------");

            while ((line = br.readLine()) != null) {
                if(line.trim().isEmpty()) continue;
                String list[] = line.split(csvSplitBy);
                int sum = 0;

                for (int i = 1; i < list.length; i++) {
                    try {
                        Integer num = Integer.parseInt(list[i]);
                        sum += num;
                    } catch (NumberFormatException nfe) {
                        // 跳过非数字字段
                    }
                }
                System.out.print(list[0] + "\t" + list[1] + "\t" + list[2]
                        + "\t" + list[3]
                        + "\t" + list[4]
                        + "\t" + list[5]
                        + "\t" + list[6]
                        + "\t" + list[7]
                        + "\n\t" + list[8]
                        + "\t" + list[9]
                        + "\t" + list[10] + "\t");

                if (sum > topScore) {
                    topScore = sum;
                    topScorer = list[0];
                }

                System.out.println(sum);
                gamerCount++;
            }

            System.out.println("----------------------------------------------------------");
            System.out.println("-------------------------------------");
            System.out.println("# of Gamers:    " + gamerCount);
            System.out.println("Top Gamer:  " + topScorer);
            br.close();
        }
    }
}
效果说明

修改后首次运行会正常添加Jimmy记录,后续重复运行程序会检测到Jimmy已存在,不会再新增重复记录,CSV中始终只会保留一条Jimmy的得分数据。

内容的提问来源于stack exchange,提问作者Jaret Daly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 01:00:00