newbie07
newbie07

Reputation: 83

java textarea and input to file

I'm having problems in my Java app. I wanted to transfer the texts in my JTextArea to a .txt file

for example I inputted

"Hi
my name is george"

I want the outcome in my .txt file to be the same

but what happens is

"Himy name is george"

Here's my code

private void btnCreateActionPerformed(java.awt.event.ActionEvent evt) {                                          
    String filename,content;
    String[] ArrContent=new String[9999];
    int wordctr=0;

    try
    {
        if(txtFilename.getText().isEmpty())
        {
            lblRequired.setText("Required Field");
        }else
        {
            lblRequired.setText(" ");
            filename=txtFilename.getText()+".txt";
            FileWriter fw=new FileWriter(filename);
            BufferedWriter writer = new BufferedWriter(fw);
            if(txtContent.getText().contains("\r\n"))
                writer.write("\r\n");
            writer.write(txtContent.getText());
            writer.close();
        }
    }

Upvotes: 0

Views: 173

Answers (2)

gprathour
gprathour

Reputation: 15333

You need to use System.lineSeparator() to write a new line to a text file.

So try something like the following

if(txtContent.getText().contains("\r\n"))
            writer.write(System.lineSeparator());

Upvotes: 0

MadProgrammer
MadProgrammer

Reputation: 347204

Try using JTextArea#write(Writer) instead...

String filename = txtFilename.getText()+".txt";
try (FileWriter fw = new FileWriter(new File(filename))) {
    txtContent.write(fw);
} catch (IOException exp) {
    exp.printStackTrace();
}

And make sure you making best efforts to close the resources that you create...

Upvotes: 2

Related Questions