Raffael
Raffael

Reputation: 33

Writing a javafx textarea to a textfile with linebreaks

So i'm currently trying to save the contents of a javafx textarea to a text file using the formatter class. The problem is that the text just gets saved in one line, without any line breaks.

This is the code i'm using for the Writing to the textFile

 File file = new File(link);
                    Formatter formatter = null;
                    try {
                        formatter = new  Formatter(file);
                    } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    formatter.format(textArea.getText() + "\n");

EDIT: I found the problem: It is the fault of Windows Notepad. When i open the txt file in a other texteditor like notepadd++, it works just fine

Upvotes: 0

Views: 864

Answers (3)

M. le Rutte
M. le Rutte

Reputation: 3563

In my project I write the contents of a TextArea as follows:

byte[] contents = area.getText().getBytes(StandardCharsets.UTF_8);
Files.createDirectories(path.getParent());
Files.write(path, contents, StandardOpenOption.CREATE);

Which saves the contents as a UTF-8 encoded text file. This includes \n. Given that I'm working on Linux, I did not check if it actually is \n\r or not, my guts tell me it is only \n.

Upvotes: 0

Sundeep
Sundeep

Reputation: 472

you have to close the formatter

formatter.close();

The Formatter output is buffered in memory first. SO you have to close your formatter once you are done.

use finally block for this

    try {
        //code
    } catch{
     //code
    }
    finally {
        formatter.close();
    }

Upvotes: 0

alext
alext

Reputation: 326

do you really need to use the Formatter class? I suppose this class produces line separators (only) for the %n placeholder (but appears to be ignoring newline characters) in the contents of the format parameter (see also the corresponding javadoc):

format(String format, Object... args)
// Writes a formatted string to this object's destination using the specified format string and arguments.

One solution might be to specify the format string as "%s%n" (indicating that you want to format a String, followed by a line break) and pass the TextArea's contents, e.g. formatter.format("%s%n", textArea.getText()), if you really need to use the formatter.

Otherwise, you may just as well directly output the contents of the textArea to the file via some Writer:

FileWriter w = new FileWriter(file);
w.write(textArea.getText());
w.close();

Upvotes: 2

Related Questions