简体   繁体   中英

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();
}

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

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

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

line = line.trim();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM