How to read from files with Files.lines(…).forEach(…)?

前端 未结 5 562
不思量自难忘°
不思量自难忘° 2020-12-03 07:53

I\'m currently trying to read lines from a text only file that I have. I found on another stackoverflow(Reading a plain text file in Java) that you can use Files.lines(..).f

5条回答
  •  心在旅途
    2020-12-03 08:26

    Sample content of test.txt

    Hello
    Stack
    Over
    Flow
    com
    

    Code to read from this text file using lines() and forEach() methods.

    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.util.stream.Stream;
    
    public class FileLambda {
    
        public static void main(String JavaLatte[]) {
            Path path = Paths.get("/root/test.txt");
            try (Stream lines = Files.lines(path)) {
                lines.forEach(s -> System.out.println(s));
            } catch (IOException ex) {
              // do something or re-throw...
            }
        }
    }
    

提交回复
热议问题