我有一个按钮可以打开一个带有默认扩展过滤器设置的保存对话框窗口,但是当用户没有在文件名上提供文件扩展名时,它应该自动添加扩展名。问题是,当这种情况发生时,文件将不会保存(或无法保存),但不会引发任何异常。文件保存成功弹出窗口告诉用户文件已成功保存,但在目录中没有找到文件。这是我的代码:
private void saveRecordsButtonActionPerformed(java.awt.event.ActionEvent evt)
{
if(evt.getSource() == this.saveRecordsButton)
{
String recordName = JOptionPane.showInputDialog(this, "Please type in the name of the record you are about to export: ", "Input Notice", JOptionPane.INFORMATION_MESSAGE);
if(recordName == null || recordName.equals(""))
{
JOptionPane.showMessageDialog(this, "You must type in the name of the record in order to save!", "Input Error!", JOptionPane.ERROR_MESSAGE);
return;
}
int returnVal = this.fileChooser.showSaveDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
//ObjectOutput oos = null;
try
{
File file = this.fileChooser.getSelectedFile();
String recordDate = this.viewByDateCB.getSelectedItem().toString();
XMLTableProducer xmlTableProducer = new XMLTableProducer(this.cbtm, "Cash Book Table", recordName, recordDate, new Date());
if(!file.getName().contains("."))
{
FileNameExtensionFilter filter = (FileNameExtensionFilter)this.fileChooser.getFileFilter();
file = new File(file.getName()+(filter.getExtensions())[0]);
System.out.println(file.getName()); //This actually prints out the exact file name with extension the way I want
}
// if file doesnt exists, then create it
if(!file.exists())
{
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw);
out.print(xmlTableProducer.getDynamicText());
out.close();
bw.close();
JOptionPane.showMessageDialog(this, "File Saved Successfully!", "Saved", JOptionPane.INFORMATION_MESSAGE);
}
catch(IOException xcp)
{
xcp.printStackTrace(System.err);
}
}
}
}