代码拉取完成,页面将自动刷新
package com.study.chap3;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
/**
* 环绕执行场景:
* 读取文件一行数据,演示一个传统的流程,如何改造成支持lambda的流程
* @author liangzj5
* @version 1.0
* @date 2021/11/2 13:51
*/
public class ExecuteAround {
private static String filePath = ExecuteAround.class.getClassLoader().getResource("data.txt").getPath();
// 传统实现:固定写死逻辑
public static String processFile() throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(filePath))){
return br.readLine();
}
}
//基于Lambda扩展
//1、行为参数化:
//1.1 引入函数式接口
@FunctionalInterface
interface ProcessFilePredicate{
String process(BufferedReader br) throws IOException ;
}
//1.2 用函数式接口传统行为
public static String processFile(ProcessFilePredicate p) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(filePath))){
return p.process(br);
}
}
public static void main(String[] args) throws IOException {
System.out.println(processFile());
System.out.println("---");
// 基于Lambda的灵活使用
String oneLine = processFile((BufferedReader br) -> br.readLine());
System.out.println(oneLine);
System.out.println("---");
int a=22;
String twoLine = processFile((BufferedReader br) -> a+br.readLine()+br.readLine());
System.out.println(a);
System.out.println(twoLine);
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。