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

FileWriter写入CSV异常:部分数据换行部分追加至行尾问题排查

问题原因分析

1. 加载用户时引入了换行符到用户名中

你的loadUsers方法使用Scanner.useDelimiter(",")分割CSV内容,但初始CSV的每行结构是用户名,加换行(比如实际字符是student1,\nstudent2,\n)。此时Scanner.next()会以逗号为分隔符,读取到的内容包含:

  • 第一个分段:student1
  • 第二个分段:\nstudent2(逗号后直接是换行,接着是student2)
  • 第三个分段:\n(最后一个逗号后的换行)

这些分段被直接作为用户名创建Student对象,导致用户列表中存在一个用户名为\nstudent2的学生。

2. 保存时未统一处理换行,保留了加载的换行符

在saveUsers方法中,你只给每个学生用户名后添加逗号,未添加换行符。当写入带换行的用户名\nstudent2时,会先输出换行,再输出student2,,紧接着后面的student3,就会被追加到这一行末尾,最终形成你看到的异常格式。

修复方案

修复加载逻辑

改为按行读取CSV,避免将换行符混入用户名:

public void loadUsers(String userDir) {
    File myFile1 = new File(userDir);
    try (Scanner scanner = new Scanner(myFile1)) {
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine().trim();
            if (line.isEmpty()) continue;
            // 移除行尾的逗号
            String username = line.replaceAll(",$", "");
            if (!username.isEmpty()) {
                addUser(new Student(username));
            }
        }
    } catch (FileNotFoundException e) {
        System.out.println("file not found");
        e.printStackTrace();
    }
}

修复保存逻辑

保存时给每个学生条目添加换行,保证每行一个用户:

public void saveUsers(String usersDir) throws IOException {
    try (FileWriter fw = new FileWriter(usersDir)) {
        for (User user : users) {
            if (user != null && user instanceof Student) {
                fw.write(String.format("%s,\n", user.getUsername()));
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

注:使用try-with-resources语法可自动关闭文件流,避免手动关闭可能引发的异常。

内容的提问来源于stack exchange,提问作者Edwin Ryerson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 03:35:42