user123 user123 - 1 year ago 84
Java Question

How do I read lines with \n from a txt file and pass as a string to JTextArea?

If I call:

JTextArea textArea = new JTextArea("test\ntest", 15, 20);

The text area will display test on 2 lines as desired.

However, when I read a line (that contains \n in the text) from a txt file using a scanner, and store it in a string to pass to the JTextArea, the text area prints the \n instead of returning a newline.

Why? I included the relevant code below.

//i.currentStats() returns a string
JTextArea textArea = new JTextArea(i.currentStats(), 15, 20);

//currentStats() uses readLastStats() to store String lastStats into String stats
public void readLastStats() {
while (sc.hasNext()) {
if ("Stats")) {
lastStats = sc.nextLine();
stats = lastStats;

The images below show the txt file & what the JTextArea prints.

Answer Source

The transmutation of the character sequence \n to a newline is performed by the Java compiler. If you create a text file with the \n sequence, then read it, it will contain the 2 character sequence, not the newline character.

If you store it as 2 separate lines. Ex:


When you read it and display it it will appear as 2 lines. If you want to store it as a single line in the file, then you'll need to provide code to process the line and replace the \n sequence with an actual newline. For example:

myExpandedString = myStringFromFile.replaceAll("\\n", "\n");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download