在java中使用filewriter保存文件时如何设置目录?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20488870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set the directory when saving file with filewriter in java?
提问by Paul K
Hi I'm using NetBeans for more easy-to-use GUI.
嗨,我正在使用 NetBeans 来获得更易于使用的 GUI。
I'm trying to save a txt file which I get the name from the user, using the FileWriter, (not using serializable)
我正在尝试使用 FileWriter(不使用可序列化)保存我从用户那里获取名称的 txt 文件
I think I could set the saving location of the file using the Serializable (I'm not sure)
我想我可以使用 Serializable 设置文件的保存位置(我不确定)
but, my code kinda looks dirty if I use Serializable and it causes some error. (I use 2 classes)
但是,如果我使用 Serializable,我的代码看起来有点脏,并且会导致一些错误。(我使用 2 个类)
Anyway, Is there a way to set the directory when saving the txt file with the FileWriter?
无论如何,有没有办法在使用FileWriter保存txt文件时设置目录?
This is my code, for saving files.
这是我的代码,用于保存文件。
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 means the directory where I want to save it, but it actually saves inside C:\Users\JSK\Desktop\BOARD
dir 表示我要保存的目录,但它实际上保存在 C:\Users\JSK\Desktop\BOARD
采纳答案by Ted Hopp
Instead of this line:
而不是这一行:
FileWriter fw = new FileWriter(str);
Try this:
尝试这个:
FileWriter fw = new FileWriter(new File(dir, str));