2016-10-19 109 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