保存文件不保存文件

问题描述:

我正在创建一个将错误日志写入文件的程序,但是当我要求保存该文件时,什么都不会发生(甚至没有例外)。我做错了什么?保存文件不保存文件

“保存” 按钮的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

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

您可能找不到该文件。

在你saveFile末,试试这个:后把

out.close(); 

一条线,像这样:

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

你会再拿到路径保存它。