Writing Contents of TextArea to File


Question

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);
}
1
2
8/1/2013 5:06:39 AM

Accepted Answer

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();
    }
5
8/2/2013 1:12:48 AM

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();
        }

    }

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon