gpt4 book ai didi

java - 使用 opencsv 需要在写入之前清除我的文件

转载 作者:行者123 更新时间:2023-11-29 05:45:23 27 4
gpt4 key购买 nike

我的问题是我填满了一个 csv 文件,但我希望每次运行我的代码时清空 csv,然后写入新数据。

每次运行代码时,都会在 FOR 循环中从我的主体调用此方法...

public static void csv_output() throws Exception {
FileWriter fw = new FileWriter("output/out.csv", true);
//true refers to append
PrintWriter pw = new PrintWriter(fw, false);
//pw.flush();
//clears the Buffer
if (Auctionhouse.current_epoch == 1) {
pw.print("Epoch");
pw.print(",");
for (int j = 0; j < Run_process.total_Agents; j++) {
pw.print(Chromosome.chromosome.get(j).ID + "_Balance");
pw.print(",");
}
for (int k = 0; k < Stockhouse.total_stocks; k++) {
pw.print(Stockhouse.stockP.get(k).stock_Id);
pw.print(",");
}
}
pw.println();
pw.print(Auctionhouse.current_epoch);
pw.print(",");
for (int i = 0; i < Run_process.total_Agents; i++) {
String ag = Portfolio.Agent_balance.get(i) + "";
pw.print(ag);
pw.print(",");
}
for (int j = 0; j < Stockhouse.total_stocks; j++) {
String pr = Auctionhouse.total_prices.get(Auctionhouse.current_epoch - 1).get(j) + "";
pw.print(pr);
pw.print(",");
}
}
pw.flush();
pw.close();
fw.close();

冲洗不起作用。

P.S:我想追加,这样我就可以在每个循环中写入数据。

最佳答案

如果要清除“output/out.csv”,只需将FileWriter 的参数更改为false 即可。

FileWriter fw = new FileWriter("output/out.csv", false);

FileWriter constructor 的文档中所述第二个参数指定是否要追加。在你的例子中,如果你想清除数据,你可以简单地传递 false 并且它将写入文件的开头。您应该在应用程序启动时执行此代码。

编辑:清除文件的内容而不删除它。如果您实现此代码,您将需要捕获 IOexception 并可能创建一个函数来执行代码,但这应该可以做到。

   public static void clearCsv() throws Exception {
FileWriter fw = new FileWriter("output/out.csv", false);
PrintWriter pw = new PrintWriter(fw, false);
pw.flush();
pw.close();
fw.close();
}

关于java - 使用 opencsv 需要在写入之前清除我的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16037942/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com