Read String line by line

前端 未结 11 1662
迷失自我
迷失自我 2020-11-29 16:38

Given a string that isn\'t too long, what is the best way to read it line by line?

I know you can do:

BufferedReader reader = new BufferedReader(new          


        
相关标签:
11条回答
  • 2020-11-29 17:12

    You can try the following regular expression:

    \r?\n
    

    Code:

    String input = "\nab\n\n    \n\ncd\nef\n\n\n\n\n";
    String[] lines = input.split("\\r?\\n", -1);
    int n = 1;
    for(String line : lines) {
        System.out.printf("\tLine %02d \"%s\"%n", n++, line);
    }
    

    Output:

    Line 01 ""
    Line 02 "ab"
    Line 03 ""
    Line 04 "    "
    Line 05 ""
    Line 06 "cd"
    Line 07 "ef"
    Line 08 ""
    Line 09 ""
    Line 10 ""
    Line 11 ""
    Line 12 ""
    
    0 讨论(0)
  • 2020-11-29 17:14

    You can use the stream api and a StringReader wrapped in a BufferedReader which got a lines() stream output in java 8:

    import java.util.stream.*;
    import java.io.*;
    class test {
        public static void main(String... a) {
            String s = "this is a \nmultiline\rstring\r\nusing different newline styles";
    
            new BufferedReader(new StringReader(s)).lines().forEach(
                (line) -> System.out.println("one line of the string: " + line)
            );
        }
    }
    

    Gives

    one line of the string: this is a
    one line of the string: multiline
    one line of the string: string
    one line of the string: using different newline styles
    

    Just like in BufferedReader's readLine, the newline character(s) themselves are not included. All kinds of newline separators are supported (in the same string even).

    0 讨论(0)
  • 2020-11-29 17:15

    Since Java 11, there is a new method String.lines:

    /**
     * Returns a stream of lines extracted from this string,
     * separated by line terminators.
     * ...
     */
    public Stream<String> lines() { ... }
    

    Usage:

    "line1\nline2\nlines3"
        .lines()
        .forEach(System.out::println);
    
    0 讨论(0)
  • 2020-11-29 17:20

    Using Apache Commons IOUtils you can do this nicely via

    List<String> lines = IOUtils.readLines(new StringReader(string));
    

    It's not doing anything clever, but it's nice and compact. It'll handle streams as well, and you can get a LineIterator too if you prefer.

    0 讨论(0)
  • 2020-11-29 17:22

    There is also Scanner. You can use it just like the BufferedReader:

    Scanner scanner = new Scanner(myString);
    while (scanner.hasNextLine()) {
      String line = scanner.nextLine();
      // process the line
    }
    scanner.close();
    

    I think that this is a bit cleaner approach that both of the suggested ones.

    0 讨论(0)
提交回复
热议问题