JAVA8 中, 新增的可以使用 Files.lines 将文件内容读取为 Stream ,从而进行操作.
文件内容如下:
c://lines.txt – A simple text file for testing
line1
line2
line3
line4
line5
- JAVA 8 Read File + Stream
public static void main(String args[]) {
String fileName = "c://lines.txt";
//read file into stream, try-with-resources
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
输出
line1
line2
line3
line4
line5
- Java8 Read File + Stream + Extra
public static void main(String args[]) {
String fileName = "c://lines.txt";
List<String> list = new ArrayList<>();
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
//1. filter line 3
//2. convert all content to upper case
//3. convert it into a List
list = stream
.filter(line -> !line.startsWith("line3"))
.map(String::toUpperCase)
.collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
list.forEach(System.out::println);
}
输出:
LINE1
LINE2
LINE4
LINE5
- 利用BufferedReader + Stream
public static void main(String args[]) {
String fileName = "c://lines.txt";
List<String> list = new ArrayList<>();
try (BufferedReader br = Files.newBufferedReader(Paths.get(fileName))) {
//br returns as stream and convert it into a List
list = br.lines().collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
list.forEach(System.out::println);
}
输出:
line1
line2
line3
line4
line5