Search code examples
javaswingnewlinejtextareajfilechooser

How to fix the New Line when saving file in a document taking text from a JTextArea


import java.awt.BorderLayout;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Formatter;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class FileDemonstrationJFileChooser extends JFrame {
    private JTextArea outputArea;
    private JScrollPane scrollPane;
    JFileChooser fileChooser = new JFileChooser();

    public FileDemonstrationJFileChooser() {
        // TODO Auto-generated constructor stub
        super("Testing class file");
        outputArea = new JTextArea();
        scrollPane = new JScrollPane(outputArea);
        add(scrollPane, BorderLayout.CENTER);
        setSize(400, 400);
        setVisible(true);

        analyzePath();

        if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
            File file = fileChooser.getSelectedFile();
            // save to file
            String toSave = outputArea.getText();
            try {
                Formatter writer = new Formatter( new File(file+".txt"));
                writer.format(toSave); //Problems here occurs
                writer.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            JOptionPane.showMessageDialog(this,
                    "Message saved.(" + file.getName() + ")", "File Saved",
                    JOptionPane.INFORMATION_MESSAGE);

        }
    }

    private File getFileOrDirectory() {

        fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        int result = fileChooser.showOpenDialog(null);
        if (result == JFileChooser.CANCEL_OPTION) {
            System.exit(1);
        }
        File fileName = fileChooser.getSelectedFile();
        if ((fileName == null) || (fileName.getName().equals(""))) {
            JOptionPane.showMessageDialog(this, "Invalid name", "Invalid name",
                    JOptionPane.ERROR_MESSAGE);
            System.exit(1);
        }
        return fileName;
    }

    private void analyzePath() {
        File name = getFileOrDirectory();
        if (name.exists()) {
            outputArea.setText(String.format(
                    "%s%s\n%s\n%s\n%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s", name
                            .getName(), " exists", (name.isFile() ? "is a file"
                            : "is not a file"),
                    (name.isDirectory() ? "is a directory"
                            : "is not a directory"),
                    (name.isAbsolute() ? "is absolute path"
                            : "is not absolute path"), "Last modified: ", name
                            .lastModified(), "Length: ", name.length(),
                    "Path: ", name.getPath(), "Absolute path: ", name
                            .getAbsolutePath(), "Parent: ", name.getParent()));

            if (name.isDirectory()) {
                String[] directory = name.list();
                outputArea.append("\n\nDirectory contents:\n");

                for (String directoryName : directory) {
                    outputArea.append(directoryName + "\n");
                }
            }
        } else {
            JOptionPane.showMessageDialog(this, name + " does not exist.",
                    "Error", JOptionPane.ERROR_MESSAGE);
        }

    }
}

My Code for Writing in a file with JFileChooser and Save it in the hard disk. But the problem occurs when writing it to the file, it does not take the new line. it saves the whole text area's text in just one line. How to fix it??

Here when i SAVE the file, it saves its content in Just ONE LINE, Not Like as in the JTextArea. That is, the new line does not appear. it saves all the content in one line. So How Can i fix it??


Solution

  • A Document will only store "\n" to represent a newline. Depending on which text component you are using the getText() method will replace the "\n" with the appropriate newline string for your platform (JTextPane) or leave the "\n" in the text (JTextArea). Check out Text and New Lines for more information.

    Don't use a Formatter to write the text. A Formatter is not aware of where the text came from.

    Instead just use the write() method provided by the JTextArea:

    FileWriter writer = new FileWriter( new File(...) );
    BufferedWriter bw = new BufferedWriter( writer );
    textArea.write( bw );
    bw.close();
    

    The write() method knows how to handle the end of line string.