1
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??

smk pobon
  • 113
  • 1
  • 12
  • Why did you ignore the advice given to you in your last question: http://stackoverflow.com/questions/33881506/saving-file-using-java-gui-in-pc-hard-disk??? – camickr Nov 24 '15 at 16:25

4 Answers4

4

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.

camickr
  • 321,443
  • 19
  • 166
  • 288
2

Don't use \n, instead use System.getProperty("line.separator") or System#lineSeparator available since Java 7, to obtain a proper line separator that depends on the platform (Windows, *nix).

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • I'm not taking the text from a hardcoded string where i will give the new line. i'm taking the text from a JTextArea. So, How can i give a new line in the file where i saving this text when a new line occurs in the JTextArea. that means i want to save all the text from a text area and save it to a file like the textArea's text format. – smk pobon Nov 24 '15 at 16:32
0

"\n" works for console output but not files. use "\r\n"(works on windows) then save it should do the trick.

Dima Maligin
  • 1,386
  • 2
  • 15
  • 30
0

A linebreak can easily insert with \r\n is the windows carriage return. So this only works for windows. You could check wich os your running and than hardcode the carriage return for every os like windows, linux,....

But hold on theres another, easier, way. Just append System.getProperty("line.separator") to the string your wirting to your file and it automatically appends the carriage return for your OS.

Hope that helps!

Felix Gerber
  • 1,615
  • 3
  • 30
  • 40
  • I'm not taking the text from a hardcoded string where i will give the new line. i'm taking the text from a JTextArea. So, How can i give a new line in the file where i saving this text when a new line occurs in the JTextArea. that means i want to save all the text from a text area and save it to a file like the textArea's text format. – smk pobon Nov 24 '15 at 16:32