I can not figure out how to save from a text frame to the current file, I have the "save as" implemented part, how can I just save to the current file? I just need to get just the path to the open file.

private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) { // Зберегти } private void saveasButtonActionPerformed(java.awt.event.ActionEvent evt) { JFileChooser chooser = new JFileChooser(); int chooserValue = chooser.showSaveDialog(this); if (chooserValue == JFileChooser.APPROVE_OPTION){ try { PrintWriter fout = new PrintWriter(chooser.getSelectedFile()); fout.printf(textArea.getText()); fout.close(); } catch (FileNotFoundException ex) { Logger.getLogger(TextEditorFrame.class.getName()).log(Level.SEVERE, null, ex); } } } 
  • In the saveasButtonActionPerformed method saveasButtonActionPerformed save the file name in the class field ( this.currentFile = chooser.getSelectedFile() ). In saveButtonActionPerformed use it ( this.currentFile ). - Nofate

1 answer 1

try this:

 JFileChooser chooser = new JFileChooser(); int chooserValue = chooser.showSaveDialog(frame); if (chooserValue == JFileChooser.APPROVE_OPTION) { try { File file = chooser.getSelectedFile(); boolean isExist = true; if (!file.exists()) isExist = file.mkdirs(); if (isExist) try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file))) { byte[] content = textArea.getText().getBytes(StandardCharsets.UTF_8); outputStream.write(content); } } catch (IOException ex) { ex.printStackTrace(); } }