Search code examples
javaswingiojtextareafilewriter

writing exact text of Jtext area to a file


hello guys i have a code in my application that save the data on the jtextarea to .txt file. The problem is when i type multiple line text on my jtextarea and save it to ".txt" file, the the whole data written as one line text.

String content = txtDescriptionCity.getText(); //jtextarea

   File file = new File("C:\\Tour v0.1\\Descriptions\\City\\"+txtcityname.getText()+".txt");


            if (!file.exists()) {
                 file.createNewFile();
            }

    FileWriter fw = new FileWriter(file.getAbsoluteFile());
    BufferedWriter bw = new BufferedWriter(fw);
    bw.write(content);
            bw.close();

i want to write the text as it is on the jtextarea... Like this

"Text line one

Text line two

Text line three"


Solution

  • If the lines where entered by Enter, do:

    content = content.replaceAll("\r?\n", "\r\n");
    

    This then uses the real line break under Windows: \r\n (CR+LF). A single \n is not shown in Notepad. Unlikely though.

    If the multiple lines were caused by word wrapping, the case is more difficult.

    If by adding spaces,

    content = content.replaceAll("  +", "\r\n");