2012-04-30 52 views
4

我有一個字符串存儲處理結果的幾個文件。如何將該字符串寫入我的項目中的.txt文件?我有另一個字符串變量是.txt文件的所需名稱。如何將字符串寫入文本文件?

+2

在問這個問題之前,您搜索了什麼? – bluesman

+1

你已經嘗試過的任何代碼示例,它沒有工作? –

+1

可能的重複[如何將字符串保存到使用Java的文本文件?](http://stackoverflow.com/questions/1053467/how-do-i-save-a-string-to-a-text-文件使用Java) –

回答

12

試試這個:

//Put this at the top of the file: 
import java.io.*; 
import java.util.*; 

//Add this to write a string to a file 
// 
try { 
    BufferedWriter out = new BufferedWriter(new FileWriter("test.txt")); 
    out.write("aString\nthis is a\nttest"); //Replace with the string 
              //you are trying to write 
} 
catch (IOException e) 
{ 
    System.out.println("Exception "); 

} 
finally 
{ 
    out.close(); 
} 
6

你的意思是?

FileUtils.writeFile(new File(filename), textToWrite); 

FileUtils在Commons IO中可用。

+1

雖然它是一箇舊的線程 - 哪個來源是你指的FileUtils? – jamesdeath123

+0

@ jamesdeath123很好的建議,謝謝。 –

2

正在使用創建基於字節流表示二進制格式的數據文件。使用基於字符的流創建的文件將數據表示爲字符序列。文本文件可以通過文本編輯器讀取,而二進制文件則通過將數據轉換爲人類可讀格式的程序讀取。

FileReaderFileWriter執行基於字符的文件I/O。

如果您使用的是Java 7,您可以使用try-with-resources縮短方法顯着:

import java.io.PrintWriter; 
public class Main { 
    public static void main(String[] args) throws Exception { 
     String str = "寫字符串到文件"; // Chinese-character string 
     try (PrintWriter out = new PrintWriter("output.txt", "UTF-8")) { 
      out.write(str); 
     } 
    } 
} 

您可以使用Java的try-with-resources語句自動接近資源(必須關閉對象時,他們不再需要)。您應該考慮資源類必須實現java.lang.AutoCloseable接口或其子接口java.lang.Closeable