문제

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"

도움이 되었습니까?

해결책 2

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");

다른 팁

Don't reinvent the wheel. Just use:

textArea.write(...);

It will replace new line characters in the Document with the proper new line string for the platform you are using.

You can split and then write, in my code i am splitting the string based on "."(fullstops).

FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
for (String retval: content.split(".")){
bw.write(retval+".");
bw.newLine();
}

First we read out the systems line seperator, then we split the content String and write each part of the new String Array to the file. The new FileWriter(*,true); garanties that the content is appended.

    String seperator = System.lineSeparator();
    String[] lines = content.split("\n");
    FileWriter writer = new FileWriter(file ,true);
    for (int i = 0 ; i < lines.length; i++){
        writer.append(lines[i]+seperator);

    }
        writer.close();
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top