我正在使用记事本在java中创建一个程序。所以我有保存,它可以工作,这里是代码
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(link.getText()));
writer.write(display.getText());
} catch (Exception e1) {
e1.printStackTrace();
} finally {
try {
if (null != writer) {
writer.close();
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
无论如何,它的作用是,你无法在代码中看到它,但是它创建了一个具有JTextField和JButton的JFrame,你所做的就是将链接放在JTextField中(例如:C:\ Users \ Noah) \ Desktop \ text.txt)并在按下保存时保存。但我想用JFileChooser来做这件事。有人能帮助我吗?
编辑:
解决方案:
JFileChooser fc = new JFileChooser("C:\\Users");
fc.showSaveDialog(frame); // frame is the JFrame (window)
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(fc.getSelectedFile().getPath()));
writer.write(display.getText());
} catch (Exception e1) {
e1.printStackTrace();
} finally {
try {
if (null != writer) {
writer.close();
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
我在发布此
之后想出了这个方法答案 0 :(得分:1)
你在谷歌有很多例子,不管怎样,这里有一些我保存xml文件的代码片段:
public void SaveMe(){
//Configure fileChooser
JFileChooser fc = new JFileChooser(lastOpenDir); // after 1st save store path to "lastOpenDir"
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.setDialogTitle("Save only XML");
fc.removeChoosableFileFilter(fc.getFileFilter()); //remove the default file filter
FileFilter filter = new FileNameExtensionFilter("XML file", "xml");
fc.addChoosableFileFilter(filter); //add XML file filter
//show dialog
int returnVal = fc.showSaveDialog(appFrame);
if(returnVal == JFileChooser.APPROVE_OPTION){
File selectedDir = fc.getSelectedFile();
lastOpenDir=fc.getSelectedFile().getParent();
lastOpenFile = fc.getSelectedFile().getName();
if(selectedDir.isFile()){
String errorString = selectedDir.getPath()+" already exists.\nDo you want to replace it?";
Object[] options = {"Yes", "No"};
int n = JOptionPane.
showOptionDialog(
null,
errorString,
"Override",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]
);
if (n == JOptionPane.YES_OPTION){
if(fc.getFileFilter().getDescription().equals("XML file")){
// save selectedDir.getPath()
}
}