![](/img/trans.png)
[英]Java FileWriter class - java.io.FileNotFoundException: * no such file or directory -Ubuntu
[英]How to set the directory when saving file with filewriter in java?
嗨,我正在將NetBeans用於更易於使用的GUI。
我正在嘗試使用FileWriter保存我從用戶那里得到的txt文件(而不使用可序列化的文件)
我想我可以使用Serializable來設置文件的保存位置(我不確定)
但是,如果我使用Serializable,我的代碼有點臟,這會導致一些錯誤。 (我使用2個班級)
無論如何,使用FileWriter保存txt文件時,是否可以設置目錄?
這是我的代碼,用於保存文件。
public boolean save() {
try {
File dir = new File("C:\\Users\\JSK\\Desktop\\BOARD\\data");
String str = Title_field.getText() + ".txt";
CheckFile(str);
CheckCbox();
area.append("\n Written at :" + date_format.format(now.getTime()));
FileWriter fw = new FileWriter(str);
fw.write(area.getText());
fw.close();
JOptionPane.showMessageDialog(this, "Successfully Written");
this.setVisible(false);
Title_field.setEditable(false);
area.setEditable(false);
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(this, "You Must Create A File First!", "File Missing", JOptionPane.ERROR_MESSAGE);
} catch (IOException ex) {
JOptionPane.showMessageDialog(this, "I/O ERROR", "Failed to save the file", JOptionPane.ERROR_MESSAGE);
} catch (FileExistException ex) {
JOptionPane.showMessageDialog(this, "File Already Exists, Please Change the title", "ERROR", JOptionPane.ERROR_MESSAGE);
area.setText("");
return false;
} catch (CheckboxSelectionException ex) {
JOptionPane.showMessageDialog(this, "You must select at least one location", "ERROR", JOptionPane.ERROR_MESSAGE);
Title_field.setText("");
area.setText("");
return false;
}
return true;
}
dir表示我要保存該目錄的目錄,但實際上保存在C:\\ Users \\ JSK \\ Desktop \\ BOARD中
代替此行:
FileWriter fw = new FileWriter(str);
嘗試這個:
FileWriter fw = new FileWriter(new File(dir, str));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.