gpt4 book ai didi

java - Java写入新文件并删除以前的数据

转载 作者:行者123 更新时间:2023-12-01 09:21:47 24 4
gpt4 key购买 nike

我正在开发一个项目,并通过spring(bean)设置文件对象,并使用Lombok的RequiredArgsConstructor来执行此操作。

代码:

Spring.xml:

<bean id=".." class="ImageDataProcess">
<constructor-arg ref="x.y.z.file.newImageDataFile" />
<other constructor args>
</bean>

ImageDataProcess.java:

@RequiredArgsConstructor
public class ImageDataProcess implements PQR {
private final File newImageDataTextFile;
//other values coming from spring
@Override
public void execute() {
://logic here
:
Forloop(){
FileUtils.writeStringToFile(newImageDataTextFile, imageDataFileLine + NEWLINE, true);
}
}
}

此图像数据文件正在形成,但每次我执行该文件时,都会附加新内容。但我只想删除文件中的新内容和旧内容。

例如,我已经通过一次程序执行创建了这个文件,大小为 2.7 MB 的 image-data.txt。当我再次执行该程序时,它使该文件 image-data.txt 大小为 5.4 MB。

我还有前后文件的内容。它有重复项。

我知道这与 bean 和 Spring 有关,就像只有一个实例正在形成一样。但问题是我希望在下一步执行后将该文件上传到服务器上。

此外,在循环中我需要附加数据。但在循环开始之前打开一个新文件以进行覆盖。

Fix:
Can I do something like have the file path from the bean(as this is always the same), but create a new file in the java file using "new File(filepath)". Will this override the existing file always?? Even if the file with the same name is present at the same location??

请告诉我如何实现此修复?它会起作用吗?我可以通过哪些方法来做到这一点?

我对 Spring 之类的东西还是新手。如有任何帮助,我们将不胜感激。

最佳答案

根据 FileUtils 文档 here

只需将您的函数调用更改为

FileUtils.writeStringToFile(newImageDataTextFile, imageDataFileLine + NEWLINE, false);

真正的 boolean 值明确告诉实用程序仅附加到文件,而不是覆盖它

关于java - Java写入新文件并删除以前的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40127972/

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