File fails to save when filename is modified
I have a button that opens a save dialog window with default extension
filters set, but when the user does not provide a file name extension on
the file name, it should add the extension automatically. The problem is
that when this happens the file will not save (or fail to save) but does
not throw any exception. The file save successfully pop-up shows up
telling the user that the file has been saved successfully but no file was
found in the directory. Here's my code:
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);
}
}
}
}
No comments:
Post a Comment