public void save(int i) { BufferedWriter brw = null; TextDocument ta = (TextDocument) td.getComponentAt(i); try { File file = null; if (ta.file == null) { // 判斷是否為新黨案,是的話使用預設路徑儲存 file = new File(default_auto_save_path + "\\" + ta.fileName); } else { file = ta.file; // 儲存於原檔案 } brw = new BufferedWriter(new FileWriter(file)); ta.write(brw); ta.save = true; td.setTitleAt(i, ta.fileName); // 更新標題名稱 } catch (FileNotFoundException ffe) { // 若預設路徑不存在,則跳出警告 JOptionPane.showMessageDialog( null, ta.fileName + "儲存失敗!\n請檢查Default AutoSave-Path是否存在,或是權限不足.", "Save error", JOptionPane.ERROR_MESSAGE); } catch (Exception exc) { exc.printStackTrace(); } finally { try { brw.close(); } catch (Exception exc) { } } }
@Override public void actionPerformed(ActionEvent e) { if (td.getTabCount() > 0) { JFileChooser f = new JFileChooser(); f.setFileFilter(new MyFileFilter()); int choose = f.showSaveDialog(getContentPane()); if (choose == JFileChooser.APPROVE_OPTION) { BufferedWriter brw = null; try { File file = f.getSelectedFile(); brw = new BufferedWriter(new FileWriter(file)); int i = td.getSelectedIndex(); TextDocument ta = (TextDocument) td.getComponentAt(i); ta.write(brw); ta.fileName = file.getName(); // 將檔案名稱更新為存檔的名稱 td.setTitleAt(td.getSelectedIndex(), ta.fileName); ta.file = file; ta.save = true; // 設定已儲存 System.out.println("Save as pass!"); td.setTitleAt(i, ta.fileName); // 更新標題名稱 } catch (Exception exc) { exc.printStackTrace(); } finally { try { brw.close(); } catch (Exception ecx) { ecx.printStackTrace(); } } } } else { JOptionPane.showMessageDialog(null, "沒有檔案可以儲存!"); } }