Read String line by line

前端 未结 11 1700
迷失自我
迷失自我 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: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).

提交回复
热议问题