2016-11-09 152 views
-2
public void saveList(Vector<Vector> table_data){ 
    ArrayList<String> output_list = new ArrayList<String>(); 
    for(int i=0;i<table_data.capacity();i++){ 
     String temp=""; 
     Vector tempVector = (Vector) table_data.elementAt(i); 
     tempVector.trimToSize(); 
     for(int v=0;v<tempVector.capacity();v++){ 
      temp+=((String)tempVector.elementAt(v))+" "; 

     } 
     temp = temp.trim(); 
     System.out.println(temp); 
     output_list.add(temp); 
    } 
    BufferedWriter bw = null; 
    FileWriter fw = null; 
    try{ 
     fw = new FileWriter(output_filename,false); 
     bw= new BufferedWriter(fw); 
     for(String i : output_list){ 
      bw.write(i); 
      bw.newLine(); 
     } 

    } 
    catch(FileNotFoundException e){} 
    finally{ 
     if (bw != null) { 
      try { 
       bw.close(); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
} 

這是我的代碼重寫文件。每次點擊它時,都會有一個JButton調用這個函數。它傳遞來自JTable的向量。該文件應該總是被覆蓋。但實際上只有在我第一次點擊按鈕時纔會覆蓋。有什麼問題,我該如何解決?Java覆蓋文件

+1

歡迎,你可以創建一個更多[mcve]比這個。 – AxelH

+1

拋出了什麼異常? – EJP

+0

由於我沒有看到問題(除了拋出IOException異常),我用一個簡單的String數組運行了你的代碼。每次運行該文件時都會使用新值重新創建該文件。所以你應該更新你的問題,如果有什麼不工作 – AxelH

回答

0

你沒有趕上IOException異常所以這並不編譯

try{ 
    fw = new FileWriteroutput_filename,false); 
    bw= new BufferedWriter(fw); 
    for(String i : output_list){ 
     bw.write(i); 
     bw.newLine(); 
    } 
} 
catch(IOException e){} 

在這個樣品和測試代碼,我用了一個掃描儀,以節省「ENTER」開頭生成不同的陣列。按下此按鍵與您的按鈕在文件中寫入相同。

public static void main(String[] args) { 
    String[][] array = new String[3][3]; //My array of test 
    for(int i = 0; i < 9; ++i){ 
     array[i/3][i%3] = "#" + i; 
    } 

    Scanner sc = new Scanner(System.in); //A scanner to way my input 
    for(String[] tmp : array){ 
     System.out.print("Press ENTER to continue"); 
     sc.nextLine(); //I am read, press "ENTER" to write in file 
     BufferedWriter bw = null; 
     FileWriter fw = null; 
     try{ 
      fw = new FileWriter("test.txt",false); 
      bw= new BufferedWriter(fw); 
      for(String s : tmp){ 
       bw.write(s); 
       bw.newLine(); 
      } 
     } 
     catch(IOException e){} 
     finally{ 
      if (bw != null) { 
       try { 
        bw.close(); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } 
     } 
    } 
} 

,其結果是: 第一次,文件與

#0 
#1 
#2 

第二次創建,文件overriten有:

#3 
#4 
#5 

,再第三次:

#6 
#7 
#8 

然後程序停止。