我是一个java初学者。我编写了一个简单的程序来使用 JFileChooser 中的 showSaveDialoge() 将一些内容写入文件。包括以下代码。
public static void main(String arg[]) throws IOException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException
{
JFrame frame = new JFrame();
JFileChooser fc = new JFileChooser();
try {
File file = new File("fileName.txt");
fc.setSelectedFile(file);
int r = fc.showSaveDialog(frame);
if(r == JFileChooser.APPROVE_OPTION)
{
FileWriter writer = new FileWriter(file);
writer.append("Data inside the file");
writer.flush();
writer.close();
}
else if(r == JFileChooser.CANCEL_OPTION) {
System.out.println("Do nothing for CANCEL");
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "File could not be written, try again.");
}
}
代码被执行,保存对话框来了。但是当我点击对话框上的保存按钮时,什么也没有发生。该文件尚未保存在所选位置。可能是什么原因。?提前致谢。