我有一個按鈕,打開一個保存對話框窗口,默認擴展名過濾器設置,但是當用戶沒有提供文件名的擴展名時,它應該自動添加擴展名。問題是,發生這種情況時文件不會保存(或保存失敗),但不會拋出任何異常。文件保存成功彈出窗口顯示告訴用戶文件已成功保存,但目錄中未找到文件。這裏是我的代碼:當文件名被修改時文件無法保存
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假設寫入過程沒有任何問題,不應該「close」沖洗輸出流(個人,我偏執,所以我都這樣做)) – MadProgrammer