0

I'm trying to create a program where you enter text into a JTextArea and then write it into a file, when I try this all it does is print everything in the JTextArea without the new lines I need a way to print it into a text file with the new lines.

FileWriter fw = new FileWriter("textfile.txt");
fw.write(jTextArea.getText());
fw.close();
mKorbel
  • 109,525
  • 20
  • 134
  • 319
New Europe
  • 31
  • 7

2 Answers2

1

JTextArea inherits the most useful write(Writer) and read(Reader, Object) methods which should make this all rather simple...

For example...

try (FileWriter fw = new FileWriter("textfile.txt")) {
    ta.write(fw);
} catch (IOException ex) {
    ex.printStackTrace();
}

For example, the following code...

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test01 {

    public static void main(String[] args) {
        new Test01();
    }

    public Test01() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }
                JTextArea ta = new JTextArea(10, 20);
                JButton btn = new JButton("Save");
                btn.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        try (FileWriter fw = new FileWriter("textfile.txt")) {
                            ta.write(fw);
                        } catch (IOException ex) {
                            ex.printStackTrace();
                        }
                    }
                });

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(ta);
                frame.add(btn, BorderLayout.SOUTH);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}

Was able to save multiple, individual lines of text in the text file, which appeared correct for Netbeans, NotePad++ and even NotePad under Windows...

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0

You need to use System.lineSeparator(); to write new line to text file.

gprathour
  • 14,813
  • 5
  • 66
  • 90