2009-06-19 46 views
36

我想重寫一個文件的內容。這是在Java中重寫文件內容的最佳方式嗎?

我所想的,到目前爲止是這樣的:

  1. 保存的文件名
  2. 刪除現有的文件
  3. 具有相同的名稱
  4. 創建一個新的空文件寫入所需內容到空文件

這是最好的方法嗎?還是有一種更直接的方式,就是不必刪除和創建文件,而只需更改內容?

回答

70

要覆蓋文件foo.log與FileOutputStream中:

File myFoo = new File("foo.log"); 
FileOutputStream fooStream = new FileOutputStream(myFoo, false); // true to append 
                   // false to overwrite. 
byte[] myBytes = "New Contents\n".getBytes(); 
fooStream.write(myBytes); 
fooStream.close(); 

或FileWriter的:

File myFoo = new File("foo.log"); 
FileWriter fooWriter = new FileWriter(myFoo, false); // true to append 
                // false to overwrite. 
fooWriter.write("New Contents\n"); 
fooWriter.close(); 
+0

@Ankur:耶。這取決於您是使用OutputStream還是Writer方法以字節爲單位編寫字符串或二進制文件。 – Stobor 2009-06-19 04:32:42

+0

是否有任何方法可用於PDF文件作家,而無需更改其名稱? – BobDroid 2012-01-06 04:49:53

+0

@BabuThangavel我不確定你在問什麼,但它看起來不像是與這個問題有關......也許你想問一個新的問題? – Stobor 2012-01-09 04:27:07

2

除非你只是在末處加入的內容,這是合理的這樣做的。如果您正在追加,請使用追加構造函數嘗試FileWriter

稍好的順序應該是:

  1. 生成新的文件名(如foo.txt.new)
  2. 寫更新內容與新的文件。
  3. 做原子重新命名foo.txt.new到foo.txt的

不幸的是,renameTo是not guaranteed做原子重新命名。

4

參見:java.io.RandomAccessFile

你要打開一個文件讀寫,所以:

RandomAccessFile raf = new RandomAccessFile("filename.txt", "rw"); 
String tmp; 
while (tmp = raf.readLine() != null) { 
    // Store String data 
} 
// do some string conversion 
raf.seek(0); 
raf.writeChars("newString"); 
1

在下面的例子中,「假」導致被覆蓋的文件,真正會導致相反。

File file=new File("C:\Path\to\file.txt"); 
DataOutputStream outstream= new DataOutputStream(new FileOutputStream(file,false)); 
String body = "new content"; 
outstream.write(body.getBytes()); 
outstream.close(); 
10

我強烈推薦使用Apache Common的FileUtil。我發現這個軟件包非常寶貴。它很容易使用,同樣重要的是,當你稍後回去時很容易閱讀/理解。

//Create some files here 
File sourceFile = new File("pathToYourFile"); 
File fileToCopy = new File("copyPath"); 

//Sample content 
org.apache.commons.io.FileUtils.writeStringToFile(sourceFile, "Sample content"); 

//Now copy from source to copy, the delete source. 
org.apache.commons.io.FileUtils.copyFile(sourceFile, fileToCopy); 
org.apache.commons.io.FileUtils.deleteQuietly(sourceFile); 

的更多信息,可以發現: http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html

1

有些時候,人們可能希望保持一個巨大的空文件,以避免操作系統分配必要的基礎上空間的額外成本。這通常由數據庫,虛擬機以及處理和寫入批量數據的批處理程序完成。這將顯着提高應用程序的性能。在這些情況下,編寫一個新文件並對其進行重命名並不會有幫助。相反,空文件將不得不被填滿。那就是當一個人必須去超越模式。

1

GuavaFile.write 「改寫用字節數組的內容的文件」:

Files.write(bytes, new File(path)); 
相關問題