Save a the text from a jTextArea (ie Save As) into a new .txt file

19,473

Solution 1

I would use the JTetArea's own write method as this will allow easy writing to file and will handle all line feeds nicely. For example (and to borrow your code):

public class TextEditor extends JFrame {

   int count = 2;
   JTextArea n = new JTextArea();
   final JFileChooser fc = new JFileChooser();

   public void SaveAs() {

      final JFileChooser SaveAs = new JFileChooser();
      SaveAs.setApproveButtonText("Save");
      int actionDialog = SaveAs.showOpenDialog(this);
      if (actionDialog != JFileChooser.APPROVE_OPTION) {
         return;
      }

      File fileName = new File(SaveAs.getSelectedFile() + ".txt");
      BufferedWriter outFile = null;
      try {
         outFile = new BufferedWriter(new FileWriter(fileName));

         n.write(outFile);   // *** here: ***

      } catch (IOException ex) {
         ex.printStackTrace();
      } finally {
         if (outFile != null) {
            try {
               outFile.close();
            } catch (IOException e) {
               // one of the few times that I think that it's OK
               // to leave this blank
            }
         }
      }
   }

}

You've got some bugs in your code. For e.g. this works,

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.io.*;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;

@SuppressWarnings("serial")
public class TextEditor extends JFrame {

   int count = 2;
   JTextArea textArea = new JTextArea(10, 30);
   final JFileChooser fc = new JFileChooser();

   public TextEditor() {
      add(new JScrollPane(textArea));
      add(new JPanel(){{add(new JButton(new AbstractAction("Save As") {

         @Override
         public void actionPerformed(ActionEvent arg0) {
            saveAs();
         }
      }));}}, BorderLayout.SOUTH);
   }

   public void saveAs() {
      FileNameExtensionFilter extensionFilter = new FileNameExtensionFilter("Text File", "txt");
      final JFileChooser saveAsFileChooser = new JFileChooser();
      saveAsFileChooser.setApproveButtonText("Save");
      saveAsFileChooser.setFileFilter(extensionFilter);
      int actionDialog = saveAsFileChooser.showOpenDialog(this);
      if (actionDialog != JFileChooser.APPROVE_OPTION) {
         return;
      }

      // !! File fileName = new File(SaveAs.getSelectedFile() + ".txt");
      File file = saveAsFileChooser.getSelectedFile();
      if (!file.getName().endsWith(".txt")) {
         file = new File(file.getAbsolutePath() + ".txt");
      }

      BufferedWriter outFile = null;
      try {
         outFile = new BufferedWriter(new FileWriter(file));

         textArea.write(outFile);

      } catch (IOException ex) {
         ex.printStackTrace();
      } finally {
         if (outFile != null) {
            try {
               outFile.close();
            } catch (IOException e) {}
         }
      }
   }

   private static void createAndShowGui() {
      TextEditor frame = new TextEditor();

      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }

}

Solution 2

You seem (though some of your code is missing) to be reading from the chosen file using FileReaderand then writing to the same file using FileWriter. Clearly, this is going around in circles.

You need to call JTextArea methods (getText() etc) to get the text, then write that to the file.

What is this.n ?

Also note that you are catching Exceptions silently with catch (IOException ex) {}, i.e. not logging any error - so you won't get any information if something goes wrong.

Finally, you should use finally to close your file - if you do it in the try block, it won't get closed if there's an Exception.

Update (now that Q has been edited): Presumably your JFileChooser is returning a directory. You are then appending ".txt" to it. I don't think this is what you meant. Try printing out fileName before writing to it. Please also print out n.getText() before writing it, and tell us what you see. Please also put a println in teh catch block so you can confirm whether there's an exception thrown.

Solution 3

you just need to close your file at the end, so it will write text into.

example:

BufferedWriter wr;
            try { wr = new BufferedWriter(new FileWriter(path));
                wr.write(edytor.getText());
                wr.close();
            } catch (IOException ex) {
                Logger.getLogger(Okno.class.getName()).log(Level.SEVERE, null, ex);
            }
Share:
19,473
user1267300
Author by

user1267300

Updated on June 14, 2022

Comments

  • user1267300
    user1267300 almost 2 years

    I am busy trying to make a word processor as one of my project and I need the text entered into the jTextArea to be saved as a .txt file with a name and location that the user chooses. note "fc" is the name of i file chooser i have already declared.

       public class TextEditor extends javax.swing.JFrame {
    
        int count = 2;
        JTextArea n = new JTextArea();
        final JFileChooser fc = new JFileChooser();
    
        public void SaveAs() {
    
            final JFileChooser SaveAs = new JFileChooser();
            SaveAs.setApproveButtonText("Save");
            int actionDialog = SaveAs.showOpenDialog(this);
    
            File fileName = new File(SaveAs.getSelectedFile() + ".txt");
            try {
                if (fileName == null) {
                    return;
                }
                BufferedWriter outFile = new BufferedWriter(new FileWriter(fileName));
                outFile.write(n.getText()); //put in textfile
    
                outFile.close();
            } catch (IOException ex) {
            }
    
        }