У меня есть кнопка, которая открывает диалоговое окно сохранения с установленными фильтрами расширения по умолчанию, но когда пользователь не предоставляет расширение имени файла в имени файла, он должен автоматически добавить расширение. Проблема в том, что когда это произойдет, файл не будет сохранять (или не сэкономить), но не вызывает никаких исключений. Всплывающее всплывающее окно сохранения файла показывает пользователю, что файл был успешно сохранен, но файл не найден в каталоге. Вот мой код:Файл не может быть сохранен при изменении имени файла
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);
}
}
}
}
После того, как вы напечатаете данные (и перед тем, как закрыть своего автора), убедитесь, что вы вызываете 'out.flush();' –
@JoshM Предполагая, что с процессом записи ничего не получается, не следует закрывать (лично, я параноик, поэтому я делаю оба;)) – MadProgrammer