Degauser
Degauser

Reputation: 120

Write JTextArea Text as String

NOTE: Thanks to user2602219 and Andrew Thompson I've solved my problem. I wish I could approve both answers right and vote up.

I've searched a lot. I've found something but they were not suitable for me.

All I want is write

Hello
World

as seen. But in my txt file it shows HelloWorld

    try{
        JTextArea area = new JTextArea();
        String path = folder+"/"+name+".txt";
        BufferedWriter output = new BufferedWriter(new FileWriter(path));
        area.write(output);
        output.close();
    }
    catch(IOException ex){}

The code above works fine. However, I've to do something before writing.

I've an encryption method (called enc). It takes a string and replaces letters wit another letters.

For example:

String text = "ABC";
String enc_text = enc(text);

//enc_text is now "ZXW";

But here is the thing. JTextArea.write looks for a "Writer" but I have to write a string because my encrypter returns a string.

Long story short. How to make

Hello
World

to this

Gteeu 
Wuazx

Upvotes: 1

Views: 497

Answers (4)

Andrew Thompson
Andrew Thompson

Reputation: 168825

  1. Take the unencrypted string from the first text area.
  2. Encrypt it.
  3. Put the encrypted string in a second text area that is not immediately visible to the end user.
  4. Use the JTextCompnent.write(..) method on the encrypted text area.

Upvotes: 1

RAJIL KV
RAJIL KV

Reputation: 399

static void writeStringToFile(File file, String data) which allows you to write text to a file in one method call.

or use FileUtils.writeStringToFile(new File("test.txt"), "Hello File");

Upvotes: 0

HishamGarout
HishamGarout

Reputation: 1763

Did you try to read each line separately and then write it on the desired txt file? This way you could use "\n" to write on a new line. Another solution that came to my mind is using the following method: String s = ""; s = s.format(something + "\n");

This way you would have lines in the string itself :)

Upvotes: 0

Robin Dijkhof
Robin Dijkhof

Reputation: 19278

Try to use this:

String text = "Hello" + "\nWorld";

\n is a new line.

Upvotes: 0

Related Questions