0

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();
        }
    }
6
  • I think there is only a \n in the textarea. Try to change: txtContent.getText().contains("\r\n") to txtContent.getText().contains("\n") Commented Jul 7, 2014 at 6:50
  • thx for the reply... it's still the same results Commented Jul 7, 2014 at 6:52
  • Use JTextArea#write(Writer) instead Commented Jul 7, 2014 at 6:53
  • I am a little surprised that you have to manually detect it and write it. Can you provide a fully compilable example that reproduces the behavior you are seeing? Commented Jul 7, 2014 at 6:53
  • @MadProgrammer sorry I just started java can u help me I didn't understand JTextAre#write(Writer) Commented Jul 7, 2014 at 6:56

2 Answers 2

2

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...

Sign up to request clarification or add additional context in comments.

4 Comments

thx... although I can't understand the difference between what I did to what you did :D but it worked! thx
Instead of trying to loop through the text content of the JTextArea and write that to the Writer, I passed the Writer to the JTextArea and allow it to handle it...
oh.. hmm if I will do this the other way around will it be the same? instead of using FileWriter will I use FileReader?
Yes, JTextArea has a read method
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.