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(..).forEach(..) However I can't actually figure out how to use the for each function to read line by line text, Anyone know where to look for that or how to do so?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Sample content of test.txt
Code to read from this text file using
lines()
andforEach()
methods.Files.lines(Path)
expects aPath
argument and returns aStream<String>
.Stream#forEach(Consumer)
expects aConsumer
argument. So invoke the method, passing it aConsumer
. 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.I have created a sample , you can use the Stream to filter/
Sample input.txt.
With Java 8, if file exists in a
classpath
:Avoid returning a list like:
Be aware that the entire file is read when 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 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.