Write JTextArea Text as String
-
26-12-2019 - |
Frage
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
Lösung
- Take the unencrypted string from the first text area.
- Encrypt it.
- Put the encrypted string in a second text area that is not immediately visible to the end user.
- Use the
JTextCompnent.write(..)
method on the encrypted text area.
Andere Tipps
Try to use this:
String text = "Hello" + "\nWorld";
\n is a new line.
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 :)
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");