2016-10-19 39 views
0

我正在处理项目,并通过spring(beans)设置文件对象,并使用Lombok的RequiredArgsConstructor来完成此操作。使用删除以前的数据写入新文件Java

代码:

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。

我也是之前和之后的文件内容。它有重复。

我知道它与豆类和春天有关,就像只有一个实例正在形成。但事情是,我想在执行后还要将这个文件上传到服务器上,下一步。

另外,在循环中我需要追加数据。但是在循环开始之前打开一个新的文件以便重写。

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

请告诉我如何才能实现此修复?并会在一切工作? 我能做到这一点的方式是什么?

我是新手和泉水。 任何帮助表示赞赏。

+0

在bean中将bean的范围设置为prototype scope =“prototype”。 –

+0

这不能解决问题:( – user2696258

回答

1

按照该文件实用程序文件here

只要改变你的函数调用

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

真正的布尔有明确的告诉工具只是追加到文件,而不是覆盖

+0

是的,我知道它是追加,但它在for循环,所以我需要追加在那里,我想在forloop开始之前有一个新的空文件 – user2696258

+0

什么可能是另一种解决方案现在呢?java甚至允许这样的事情吗? – user2696258

+0

然后只是删除文件,如果它存在for循环之前:) for循环的第一次迭代将创建该文件(假设writeStringToFile方法创建文件,如果它不'如果不存在,你必须手动创建文件),然后附加到它。 因此,每次调用方法时,它都会擦除旧文件,创建一个新文件,然后对其进行附加。 – zack6849