Java IO & NIO Java Java API
Class:
java.nio.file.Files
Methods:
public static Stream<String> lines(Path path)
throws IOException
public static Stream<String> lines(Path path,
Charset cs)
throws IOException
Read all lines from a file as a Stream .
- Parameters:
-
path
- the path to the file
-
cs
- the charset to use for decoding
- Returns:
- the lines from the file as a
Stream
Examples
package com.logicbig.example.files;
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.stream.Stream;
public class LinesExample {
public static void main(String... args) throws IOException { Path path = getFilePathToRead(); Stream<String> lines = Files.lines(path); lines.forEach(System.out::println); }
public static Path getFilePathToRead() throws IOException { Path tempFile = Files.createTempFile("test-file", ".txt"); Files.write(tempFile, "line1\nline2\n".getBytes()); return tempFile; } }
Outputline1 line2
package com.logicbig.example.files;
import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.stream.Stream;
public class LinesExample2 {
public static void main(String... args) throws Exception { Path path = getFilePathToRead(); Stream<String> lines = Files.lines(path, Charset.forName("UTF-16")); lines.forEach(System.out::println); }
public static Path getFilePathToRead() throws IOException { Path tempFile = Files.createTempFile("test-file", ".txt"); Iterable iterable = Arrays.asList("line1", "line2"); Files.write(tempFile, iterable, Charset.forName("UTF-16")); return tempFile; } }
Outputline1 line2
|
|