TheSuds13
TheSuds13

Reputation: 347

How would I create a string that has the same spaces and new lines as a text document?

I'm using a scanner class to read a text file. I want the string to have the same amount of spaces and new lines so that I can fit it into a JTextArea. Here's what I have so far:

public String getText(){
    String text = "";

    while(read.hasNextLine()){
        text += read.nextLine();

    }

    return text;
}

When I added + '\n' it just added white spaces and not new lines.

Upvotes: 1

Views: 32

Answers (3)

jiaweizhang
jiaweizhang

Reputation: 819

The read.nextLine() removes the \n character. So you have to add it back in with text += read.nextLine() + "\n";

So the full code will be:

public String getText(){
    String text = "";

    while(read.hasNextLine()){
         text += read.nextLine() + "\n";

    }

    return text;
}

Edit: As shown here you can replace \n with \r\n like content = content.replaceAll("(?!\\r)\\n", "\r\n");

Upvotes: 1

camickr
camickr

Reputation: 324147

I'm using a scanner class to read a text file.

Don't use a Scanner. There is no need to parse the file into lines of data.

Instead use a Reader, then you can use the read(...) method of a JTextArea to read the file:

JTextArea edit = new JTextArea(30, 60);
FileReader reader = new FileReader( "TextAreaLoad.txt" );
BufferedReader br = new BufferedReader(reader);
edit.read( br, null );
br.close();

Upvotes: 2

Brandon White
Brandon White

Reputation: 1005

You can actually add the newline back to your JTextArea by appending text string with the return value of System.getProperty("line.separator");. This is recommended as it returns the system-dependent line-feed and/or return carriage characters.

The nextLine() method actually strips any line-feeds and carriage return characters from your String.

Upvotes: 1

Related Questions