John Stef
John Stef

Reputation: 595

Reading from text file and storing contents into a list Java

I have a text file that contains values in the following form and what I'm trying to do is to insert the two elements of each line into a list, but by removing the spaces that appear before the first element.

What I have (text file):

 290729 one
  79076 12345
  76789 hi
    462 nick

What I'm trying to do using the list:

[290729 one,79076 12345,76789 hi,462 nick]

instead of

[ 290729 one,  79076 12345,  76789 hi   ,    462 nick] 

Is this a reasonable action or it is not necessary? The reason I'm asking is because I intent to use the two values of each line later on and I think since the spaces before the first value are not equal for every element of the list it might be a problem in picking the first value whereas all the second values have only one space before them.

Here is my code so far:

List<String> list = new ArrayList<>();
try {
        StringBuilder sb = new StringBuilder();
        String line;

        while ((line = br.readLine()) != null) {
            sb.append(line);
            sb.append(System.lineSeparator());
            list.add(line);             
        }
finally {
   br.close();
}

Upvotes: 2

Views: 59

Answers (3)

NickD
NickD

Reputation: 506

You can 'trim' whitespace from the start and end of strings using the 'trim' method:

line = line.trim();

Upvotes: 1

Tim Johnson
Tim Johnson

Reputation: 287

What I believe you need is to call the java string trim() method on the lines you gets.

Reference: https://www.tutorialspoint.com/java/java_string_trim.htm

Upvotes: 1

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285430

Looks like a simple trim() is all you need! list.add(line.trim());

Upvotes: 2

Related Questions