Writing to a new file with erasing previous data Java

馋奶兔 提交于 2020-01-25 21:09:05

问题


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

Code:

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.

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.

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

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


回答1:


As per the FileUtils documentation here

Just change your function call to

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



来源:https://stackoverflow.com/questions/40127972/writing-to-a-new-file-with-erasing-previous-data-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!