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

如何确保文件写入方法仅请求一次文件名并批量写入所有对象数据

解决多次输入文件名&多文件生成的问题

这个问题的核心是你把文件创建的逻辑和单个员工数据写入的逻辑混在一起了——每次调用writeData()都会触发文件名输入和新文件创建,遍历列表时自然会多次弹出提示,还会生成多个文件。我们可以通过拆分职责来解决:

步骤1:重构父类的writeData()方法

把文件创建的逻辑从writeData()里抽出来,让这个方法只负责写入当前员工的数据,文件的打开/关闭交给外部统一处理。修改后的父类代码:

public class Employee {
    protected String name;
    protected String employeeNum;
    protected String department;
    protected char type;

    // 移除原有的printer成员变量,改为接收外部传入的BufferedWriter
    public void writeData(BufferedWriter printer) throws IOException {
        String data = getData();
        printer.write(data);
        printer.newLine(); // 每个员工数据单独一行,避免内容挤在一起
    }

    protected String getData() {
        return name + " " + employeeNum + " " + department + " " + type;
    }
}

步骤2:子类保持getData()的重写不变

你的Commission子类(以及Hourly、Salary)的getData()重写逻辑是没问题的,不需要修改:

public class Commission extends Employee {
    private int weeksStart;
    private double baseWeeklySalary;
    private double salesWeekly;
    private double totalSales;
    private double commissionRate;

    @Override
    protected String getData() {
        return name + " " + employeeNum + " " + department + " " + type + " " + weeksStart + " " + baseWeeklySalary + " " + salesWeekly + " " + totalSales + " " + commissionRate;
    }
}

步骤3:统一处理文件创建和遍历写入

在遍历Employee列表的入口处,只做一次文件名输入和文件初始化,然后把同一个BufferedWriter传给每个员工的writeData()方法:

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class EmployeeManager {
    public static void main(String[] args) throws IOException {
        List<Employee> employees = new ArrayList<>();
        // 这里添加你的Commission、Hourly、Salary类型员工实例

        // 只执行一次文件名输入
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter the name of the new file for next week");
        String newFile = sc.nextLine();
        
        // 使用try-with-resources自动关闭文件资源,避免内存泄漏
        try (BufferedWriter printer = new BufferedWriter(new FileWriter(newFile + ".txt"))) {
            // 遍历所有员工,写入同一个文件
            for (Employee emp : employees) {
                emp.writeData(printer);
            }
        }
    }
}

为什么这样改?

  • 职责单一:writeData()只负责写入单个员工的数据,文件的管理逻辑集中在一处,代码更清晰
  • 避免重复操作:文件名只输入一次,文件只创建/打开一次,不会多次弹出提示
  • 资源安全:try-with-resources会自动帮你关闭BufferedWriter,不用手动处理close(),减少出错概率

内容的提问来源于stack exchange,提问作者Mac McGuy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:58:04