Iam是java初學者。 我寫了一個簡單的程序,使用JFileChooser中的showSaveDialoge()將一些內容寫入文件。代碼包括下面。未在Java中使用JFileChooser保存文件
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.");
}
}
該代碼被執行並且保存對話框已經到來。但是當我點擊「對話框」上的「保存」按鈕時,什麼都沒有發生。該文件沒有保存在選定的位置。可能是什麼原因? 在此先感謝。
非常感謝RamonBoza。它的工作。然後標記爲: – Sajeev
標記爲:P – RamonBoza