Mark Nutt
Mark Nutt

Reputation: 358

Writing Contents of TextArea to File

I'm currently converting all my old applications in Java that use the "J" components to the newer, more trendy JavaFX platform.

Previously in one of my application, you were able to write the contents of a TextArea to a file,nicely spaced an indented, as you graphically saw it in the text area. You did this by using the write() method that the JTextArea class inherited.

Is there anyway to do this with a JavaFX text area, or can I even be able to parse through the file and do it that way?

Assistance would be greatly appreciated!

Code used in JTextArea to write files:

public static void writeFile(File fileName) throws IOException{
    BufferedWriter fileOut = new BufferedWriter(new FileWriter(fileName));
    Gui.getTextArea().write(fileOut);
}

Upvotes: 2

Views: 8329

Answers (2)

Reegan Miranda
Reegan Miranda

Reputation: 2949

Try this code

public void fileWriter(File savePath, TextArea textArea) {
        try {
            BufferedWriter bf = new BufferedWriter(new FileWriter(savePath));
            bf.write(textArea.getText());
            bf.flush();
            bf.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

Upvotes: 0

amaurs
amaurs

Reputation: 1642

You can do that by iterating over the text area and writing the contents into a file:

    ObservableList<CharSequence> paragraph = textArea.getParagraphs();
    Iterator<CharSequence>  iter = paragraph.iterator();
    try
    {
        BufferedWriter bf = new BufferedWriter(new FileWriter(new File("textArea.txt")));
        while(iter.hasNext())
        {
            CharSequence seq = iter.next();
            bf.append(seq);
            bf.newLine();
        }
        bf.flush();
        bf.close();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }

Upvotes: 5

Related Questions