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

前端 未结 5 543
不思量自难忘°
不思量自难忘° 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:16

    Files.lines(Path) expects a Path argument and returns a Stream<String>. Stream#forEach(Consumer) expects a Consumer argument. So invoke the method, passing it a Consumer. That object will have to be implemented to do what you want for each line.

    This is Java 8, so you can use lambda expressions or method references to provide a Consumer argument.

    0 讨论(0)
  • 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<String> lines = Files.lines(path)) {
                lines.forEach(s -> System.out.println(s));
            } catch (IOException ex) {
              // do something or re-throw...
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-03 08:27

    I have created a sample , you can use the Stream to filter/

    public class ReadFileLines {
        public static void main(String[] args) throws IOException {
            Stream<String> lines = Files.lines(Paths.get("C:/SelfStudy/Input.txt"));
    //      System.out.println(lines.filter(str -> str.contains("SELECT")).count());
    
    //Stream gets closed once you have run the count method.
            System.out.println(lines.parallel().filter(str -> str.contains("Delete")).count());
        }
    }
    

    Sample input.txt.

    SELECT Every thing
    Delete Every thing
    Delete Every thing
    Delete Every thing
    Delete Every thing
    Delete Every thing
    Delete Every thing
    
    0 讨论(0)
  • 2020-12-03 08:32

    Avoid returning a list with:

    List<String> lines = Files.readAllLines(path); //WARN
    

    Be aware that the entire file is read when Files::readAllLines is called, with the resulting String array storing all of the contents of the file in memory at once. Therefore, if the file is significantly large, you may encounter an OutOfMemoryError trying to load all of it into memory.

    Use stream instead: Use Files.lines(Path) method that returns a Stream<String> object and does not suffer from this same issue. The contents of the file are read and processed lazily, which means that only a small portion of the file is stored in memory at any given time.

    Files.lines(path).forEach(System.out::println);
    
    0 讨论(0)
  • 2020-12-03 08:35

    With Java 8, if file exists in a classpath:

    Files.lines(Paths.get(ClassLoader.getSystemResource("input.txt")
                        .toURI())).forEach(System.out::println);
    
    0 讨论(0)
提交回复
热议问题