Java 如何使用JFileChooser保存txt文件
嘿,我想做一个记事本类型的程序,但我无法保存文件,你能帮我吗Java 如何使用JFileChooser保存txt文件,java,Java,嘿,我想做一个记事本类型的程序,但我无法保存文件,你能帮我吗 save.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent event){ saveFile(); if(fileToSave == JFileChooser.APPROVE_OPTION){ try{
save.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
saveFile();
if(fileToSave == JFileChooser.APPROVE_OPTION){
try{
BufferedWriter out = new BufferedWriter(new FileWriter(Save.getSelectedFile().getPath() + ".txt"));
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
});
public void saveFile(){
JFileChooser save = new JFileChooser();
int option = save.showSaveDialog(this);
fileToSave = option;
Save = save;
}
File dir = null;
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int resp = fc.showOpenDialog(null);
if (resp == JFileChooser.APPROVE_OPTION) {
dir = fc.getSelectedFile();
}
File file = new File(dir, "my-file.txt");
FileWriter fw = null;
try {
fw = new FileWriter(file);
fw.write("my first line\r\n");
fw.write("my second line");
fw.flush();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if(fw != null) {
try {
fw.close();
} catch (IOException ex) {
}
}
}
无法保存文件
您能详细描述一下吗?您是否看到一些错误/异常?还有saveFile
方法代码是什么样子的?初始化的fileToSave
是什么,在哪里?它只创建了一个空白文件,我刚刚添加了saveFile方法。好吧,我没有看到任何代码使用您的bufferedwriterout
。如果它不知道应该使用哪些数据,为什么你会期望它将数据写入文件?我对这一点很陌生,我正在遵循一个教程,我希望用户能够选择位置和文本,以便将其嵌入到程序中不会起作用。还有其他想法吗