2014-02-14 118 views
2

如何使用FileWriter實際寫入文件,然後在記事本中打開並查看我寫的內容?這是我試過到目前爲止:FileWriter寫入文件

package Experimental; 

import java.io.*; 

public class IO { 

    public static void main (String args[]) { 

     File f = new File("testFile.txt"); 

     //Outputting into a file 
     try { 

      PrintWriter filePrint = new PrintWriter(
      new BufferedWriter(new FileWriter(f,true)) 
     ); 
      filePrint.println("testing, testing, printing into a file (apparently)"); 
     } catch (IOException e) { 
      System.out.println(e.getMessage()); 
     } 
    } 
} 
+0

提高您的格式,請 – BackSlash

+0

如果你用記事本打開該文件,會發生什麼?它打開它嗎? – RaviH

+1

什麼問題? –

回答

7

不要忘了你的close一旦FileWriter你寫完它。

+0

我認爲'flush'也很重要。 –

+1

調用'close'會自動刷新一個流。 –

0

你應該沖洗接近PrintWriter這樣的:

File file = new File("testFile.txt"); 
PrintWriter filePrint = new PrintWriter(new BufferedWriter(new FileWriter(file, true))); 

try 
{ 
    try 
    { 
    filePrint.println("testing, testing, printing into a file (apparently)"); 
    filePrint.flush(); 
    } 
    finally 
    { 
    filePrint.close(); 
    } 
} 
catch (IOException e) 
{ 
    e.printStackTrace(); 
} 
+0

爲什麼要在那裏嘗試一些特殊的理由? – Betlista

+0

@Betlista'close'方法可以拋出'IOException' –