2014-02-22 63 views
1
public void updateF()throws Exception 
{ 
    int i; 
    BufferedWriter outputWriter = null; 
    outputWriter = new BufferedWriter(new FileWriter(getClass().getResource("valS.txt").getFile())); 
    for (i = 0; i < Status.length-1; i++) 
    { 
      outputWriter.write(Status[i]+","); 
    } 
    outputWriter.write(Status[i]); 
    outputWriter.flush(); 
    outputWriter.close(); 
} 

我試圖更新一個文件「valS.txt」,其中存在所有我的.java文件。此代碼編譯但不更新任何內容。我認爲路徑不可達。幫幫我!!從java文件更新文本文件

+1

有沒有錯誤?異常? – Keerthivasan

+0

沒有更新文件:( – rick

+0

我認爲這行「getClass()。getResource(」valS.txt「)。getFile()」有一些問題 – rick

回答

0

假設你的狀態數組不爲空,這段代碼將工作,但該文件的文本文件將在編譯/輸出目錄

所以在源目錄中的文本文件,將不會更新更新,但輸出目錄中的那個將會。

還要注意的是FileWirter的構造函數,你正在使用將覆蓋該文件的內容,所以你應該使用一個與append參數:

public FileWriter(String fileName, boolean append) throws IOException 

編輯:如果你真的需要更新文件在src目錄中,你可以像這樣做。

不是真的不錯,但這種將工作

public void updateF()throws Exception 
{ 

    String fileName = "valS.txt"; 
    File fileInClasses = new File(getClass().getResource(fileName).getFile()); 
    System.out.println(fileInClasses.getCanonicalPath()); 
    File f = fileInClasses; 
    boolean outDir = false; 

    // let's find the output directory 
    while(!outDir){ 
     f = f.getParentFile(); 
     outDir = f.getName().equals("out"); 
    } 

    // get the parent one more time 
    f = f.getParentFile(); 

    // from there you should find back your file 
    String totoPath = f.getPath()+"/src/com/brol/" + fileName; 
    File totoFile = new File(totoPath); 

    BufferedWriter outputWriter = null; 
    outputWriter = new BufferedWriter(new FileWriter(totoFile, true)); 
    outputWriter.append("test"); 
    outputWriter.flush(); 
    outputWriter.close(); 
} 
+0

有沒有辦法在我的源代碼目錄中更新? – rick

+0

我沒有看到另一種方式,而不是硬編碼文件的路徑 –

+0

我無法硬編碼路徑:-( – rick

0
  FileWritter, a character stream to write characters to file. By default, it will 
     replace all the existing content with new content, however, when you specified a true (boolean) 
     value as the second argument in FileWritter constructor, it will keep the existing content and 
     append the new content in the end of the file. 
     fout = new FileWriter("filename.txt", true); 
     the true is enabling append mode . 

write Like: 
BufferedWriter outputWriter = null; 
outputWriter = new BufferedWriter(new FileWriter(getClass().getResource("valS.txt").getFile(),true)); 
1

outputWriter =新的BufferedWriter(新的FileWriter(valS.txt));

嘗試使用它來代替: outputWriter = new BufferedWriter(new FileWriter(getClass()。getResource(「valS.txt」)。getFile()));