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

Java使用OpenCSV写入CSV文件的问题解决与实现示例

问题已解决

我已通过在对应方法中应用如下代码解决了遇到的问题,因此对原有提问内容进行了更新,目前问题已解决。

核心修复逻辑

新增文件存在性判断,避免不同表写入CSV时内存缓存数据交叉污染:

if (!file.exists())
    theRows.clear();

完整实现代码

@Repository
public class DatabaseImpl implements Database {

    List<String[]> theRows = new ArrayList<>();


    @Override
    public int insert(String tableName, List<String> values) {
        File file = new File(tableName + ".csv");
        if (!file.exists()) {
            prepareCsvFileAndInsertDataToCsvFile(values, file);
        } else {
            prepareCsvFileAndInsertDataToCsvFile(values, file);
        }
        return 0;
    }

    private void prepareCsvFileAndInsertDataToCsvFile(List<String> values, File file) {
        if (!file.exists())
            theRows.clear();
        try (CSVWriter writer = new CSVWriter(new FileWriter(file))) {
            String[] header = new String[]{"id", "name", "surname", "age", "salary"};
            theRows.add(values.toArray(String[]::new));//arasdiracam
            writer.writeNext(header);
            writer.writeAll(theRows, false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void update(String tableName, int rowId, List<String> values) {

    }

    @Override
    public List<String> select(String tableName, int rowId) {
        return null;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 01:01:10