2013-04-20 142 views
1

我正在創建一個將錯誤日誌寫入文件的程序,但是當我要求保存該文件時,什麼都不會發生(甚至沒有例外)。我做錯了什麼?保存文件不保存文件

「保存」 按鈕的ActionListener:

public void actionPerformed(ActionEvent arg0) { 
    String savePath = getSavePath(); 

    try { 
     saveFile(savePath); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

} 

和三個文件的方法:

private String getSavePath() { 
    JFileChooser fc = new JFileChooser(); 
    fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); 

    fc.showOpenDialog(this); 

    return fc.getSelectedFile().getAbsolutePath(); 

} 

private void saveFile(String path) throws IOException { 
    File outFile = createFile(path); 

    FileWriter out = null; 

    out = new FileWriter(outFile); 

    out.write("Hey"); 

    out.close(); 

} 

private File createFile(String path) { 
    String fileName = getLogFileName(path); 
    while (new File(fileName).exists()) { 
     fileCounter++; 
     fileName = getLogFileName(path); 

    } 

    File outFile = new File(fileName); 
    try { 
     outFile.createNewFile(); 
    } catch (IOException e) { 
     e.printStackTrace(); 

    } 

    return outFile; 

} 

private String getLogFileName(String path) { 
    return "enchantcalc_err_log_" + fileCounter + ".txt"; 
} 
+1

當你進行一些調試時,你是否達到了「點擊」動作? – Zakaria 2013-04-20 20:40:37

+0

您是否添加()'ActionListener'? – jlordo 2013-04-20 20:41:31

回答

3

getLogFileName(...)功能是不是做你給它的路徑任何東西。因此,您正試圖將文件寫入enchantcalc_err_log_#.txt(沒有實際路徑)。試試這個:

private String getLogFileName(String path) { 
    return path + "enchantcalc_err_log_" + fileCounter + ".txt"; 
} 
+0

謝謝你!我真的很困惑......哦,我在路徑和名稱之間加了一個分隔符。 – Creator13 2013-04-21 08:27:16

+0

我有一種感覺,你可能需要它 – supersam654 2013-04-21 19:19:13

2

您可能找不到該文件。

在你saveFile末,試試這個:後把

out.close(); 

一條線,像這樣:

out.close(); 
System.out.println("File saved to: "+outFile.getAbsolutePath()); 

你會再拿到路徑保存它。