通过擦除先前的数据Java写入新文件 [英] Writing to a new file with erasing previous data Java

查看:83
本文介绍了通过擦除先前的数据Java写入新文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个项目,并通过spring(beans)设置文件对象,并使用Lombok的RequiredArgsConstructor进行设置.

I am working on a project, and having file object set through spring (beans), and using RequiredArgsConstructor of Lombok to do so.

代码:

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);
        }
    }
}

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

This image-data file is getting formed, but everytime I execute the file the new contents are getting appended. But I want only the new contents in the file and old contents to be erased.

因此,例如,我已经通过一次执行该程序将文件制作为2.7 MB的image-data.txt. 当我再次执行该程序时,它将使该文件作为image-data.txt变为5.4 MB.

So for example, I already have this file made by one execution of the program as image-data.txt of 2.7 MB. When I execute this program the another time, it makes this file as image-data.txt as 5.4 MB.

我之前和之后的文件内容也是如此.它有重复项.

I also the content of the files before and after. It has duplicates.

我知道它与bean和spring有关,就像仅形成一个实例一样.但问题是,我还希望执行后的该文件也可以在下一步中上传到服务器上.

I know it has something to do with beans and spring, like only one instance is getting formed. But the thing is I want this file after the execution also, to be uploaded on a server, in the next step.

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

Also, in the loop I need to append the data. But make a new file opened for over writing before the loop begins.

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??

请告诉我如何才能解决此问题??它会全部工作吗? 我有什么方法可以做到这一点?

Please tell me how I can achieve this fix?? and will it at all work?? What are the ways I can do this??

我是Spring和所有人的新手. 感谢您的帮助.

I am novice to springs and all. Any help is appreciated.

推荐答案

根据FileUtils文档

As per the FileUtils documentation here

只需将函数调用更改为

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

真正的布尔值是明确告诉实用程序将其追加到文件中,而不是覆盖文件

The true boolean there is explicitly telling the utility to just append to the file, rather than overwrite it

这篇关于通过擦除先前的数据Java写入新文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆