java - 尝试使用 Java 更新 CSV 文件,但文件大小不断增加,尽管代码清空了其内容
问题描述
我正在使用 Java 进行编码,并且正在尝试将一些外汇数据写入 CSV 文件。我希望 CSV 文件始终是最新的 277 个数据,而不是堆叠在旧数据之上。所以我使用了“new FileWriter(file, false).close();” 每次在程序写入数据之前清空之前的数据。该代码的工作原理是最新数据始终从用 excel 打开的 CSV 中的索引 1 开始,其余为空白。但是 csv 文件大小不断增加。谁能给我有关如何修改代码以使文件大小不会无限增加的任何想法?
//this is the inside of a loop that starts every time a candle stick gets formed
try {
new FileWriter(file, false).close();
} catch (Exception e) {
console.getErr().println(e.getMessage());
e.printStackTrace(console.getErr());
context.stop();
}
int shift = 1;
while (shift < 278){
IBar bar = history.getBar(Instrument.USDJPY, Period.FIVE_MINS, OfferSide.BID, shift);
try {
out.write(dateFormat.format(bar.getTime()) + "," + priceFormat.format(bar.getOpen()) + "," + priceFormat.format(bar.getHigh()) + ","
+ priceFormat.format(bar.getLow()) + "," + priceFormat.format(bar.getClose()) + "," + priceFormat.format(askBar.getVolume()) + "\r\n");
} catch (Exception e) {
console.getErr().println(e.getMessage());
e.printStackTrace(console.getErr());
context.stop();
}
shift+=1;
}//while
try {
out.flush();
} catch (Exception e) {
console.getErr().println(e.getMessage());
e.printStackTrace(console.getErr());
context.stop();
}
编辑:我用记事本打开了 CSV,看到了巨大的空间,不得不向下滚动很远才能看到数据。当我打开 CSV 文件的属性时,大小为 253 KB,但“磁盘大小”为 3.87 mb,我不明白。无论如何要解决这个问题?
Edit2:停止 Fx 平台应用程序上的程序运行大概关闭了名为“out”的 Bufferwriter,并且“磁盘上的大小”恢复正常。但仍然不知道空间问题。不知何故,我无法用记事本手动编辑它,它说我在尝试保存时无权更改文件。我是编程新手,所以我也不知道那是什么。谢谢你。
编辑3:解决了。out.flush 是罪魁祸首,将其替换为 out.close,并在每次启动此类时创建一个名为“out”的新缓冲区写入器。
解决方案
推荐阅读
- git - 我需要一种 100% 确定的方法来使我的 GitHub 分叉和克隆与原始版本相同吗?
- mysql - 在 mySQL 中运行的奇怪正则表达式
- python-3.x - 从引发错误的同一点继续执行脚本
- .net - [MsTeams][BotFrameworkV4][Adaptive Card ] 团队中可滚动的自适应卡片
- regex - 如何通过 TYPO3 的重定向模块重定向以特定路径开头的 URL?
- android - 处理程序 - PostDelayed 方法“破坏”其余(块)代码?
- javascript - 如何将图表输入值格式,而不是百分比格式
- r - 如何在 R 函数中操作变量名称?
- tensorflow - 张量板数据
- mysql - 带有损坏子查询的 Sql 查询返回结果