[英]File not saved using JFileChooser in Java
我是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());
嘗試這個:
FileWriter writer = new FileWriter(fc.getSelectedFile());
它應從文件選擇器寫入所選文件。
您正在寫入fileName.txt,它將保存在運行程序的當前目錄中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.