2015-05-01 70 views
2

漂亮的自我解釋性標題。爲什麼我的程序不能將文本寫入.txt文件?代碼如下:爲什麼我的代碼會創建一個.txt文件,但不會在其中寫入信息?

package juego; 
import java.io.*; 
/** 
* 
* @author Administrador 
*/ 
public class Archivo 
{ 
    public void crearArchivo() 
    { 
    try 
    { 
     FileWriter fw = new FileWriter("ReglasDelTablero.txt"); 
     PrintWriter pw = new PrintWriter(fw); 

     pw.println("<7,0> , <0,0>"); 
     pw.println("<4,1> , <7,2> | <2,7> , <5,5> | <1,2> , <7,4> | <0,4> , <2,5>"); 
     pw.println("<7,7> , <3,6> | <6,4> , <3,5> | <4,0> , <2,1> | <2,4> , <0,3>"); 
    } 
    catch(IOException e) 
    { 
     System.out.println("error"); 
    } 
} 
} 
+1

可能的重複[Printwriter not writing to outputStream](http://stackoverflow.com/questions/8088219/printwriter-not-writing-to-outputstream) – Lutz

回答

5

您必須關閉編寫器,以便更改顯示在文本文件中。 finally塊確保即使發生錯誤也會發生這種情況。

try { 
    FileWriter fw = new FileWriter("ReglasDelTablero.txt"); 
    PrintWriter pw = new PrintWriter(fw); 

    //... 
} catch (IOException e) { 
    //... 
} finally { 
    pw.close(); 
    fw.close(); 
} 

或者你也可以使用一個try-with-resources statement,它會自動關閉作家:

try (FileWriter fw = new FileWriter("ReglasDelTablero.txt"); 
    PrintWriter pw = new PrintWriter(fw);) 
{ 
    //... 
} catch (IOException e) { 
    //... 
} 
0

試試這個

package juego; 
import java.io.*; 
/** 
* 
* @author Administrador 
*/ 
public class Archivo 
{ 
    public void crearArchivo() 
    { 
     PrintWriter pw = null; 
    try 
    { 
     pw = new PrintWriter(new FileWriter("ReglasDelTablero.txt"));//onle line chain 


     pw.println("<7,0> , <0,0>"); 
     pw.println("<4,1> , <7,2> | <2,7> , <5,5> | <1,2> , <7,4> | <0,4> , <2,5>"); 
     pw.println("<7,7> , <3,6> | <6,4> , <3,5> | <4,0> , <2,1> | <2,4> , <0,3>"); 
    } 
    catch(IOException e) 
    { 
     System.out.println("error"); 
    }finally{ 

     if(pw!=null){ 
       try{ pw.close();...catch 
     } 

    } 

的try-catch rsources是罰款,某些情況下,但是這是舊的方式和更好的工作,當你有一個以上的1個例外

+1

如果有多個異常,是什麼讓你覺得這樣更好?您可以在try-with-resources塊中捕獲多個異常... –

+0

如果您需要從池中獲取可引發異常的Connection對象,然後從該語句中獲取一條語句和一條記錄集......然後根據如果調用fn1與數據庫結果或fn2 ... – tgkprog

+1

我不明白如何任何這是不使用嘗試與資源的原因。 –

相關問題