我是 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.");
}
}
代码被执行,保存对话框出现。但是当我点击对话框上的保存按钮时,什么也没有发生。该文件尚未保存在所选位置。可能是什么原因? 提前致谢。
最佳答案
发生的事情是:
您在当前位置创建一个名为 fileName.txt 的文件
File file = new File("fileName.txt"); //could be $HOME$/fileName.txt
用户选择ProgramFiles/file.txt
但您使用的是 FileWritter 文件信息,而不是用户从 FileChooser 中选择的信息。
改变
FileWriter writer = new FileWriter(file);
到
FileWriter writer = new FileWriter(chooser.getSelectedFile());
关于java - 文件未在 Java 中使用 JFileChooser 保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19377824/