
【六袆-Java】使用函数式接口处理文件内容|文件控制台打印
发布日期:2021-05-07 00:44:24
浏览次数:27
分类:原创文章
本文共 1607 字,大约阅读时间需要 5 分钟。
学编程需要动力啊!
第一:自定义一个函数式接口
FileConsumer
/** * Created by 肖橙橙 * CreateTime 2020-07-27 14:09 * 文件处理函数式接口 */@FunctionalInterfacepublic interface FileConsumer { /** * 抽象方法 * 接收的是一个文件对象 * @param fileContent 文件内容的字符串 */ void FileHandler(String fileContent);}
第二:创建一个文件服务类
FileService
package xyz.cc2020.sku.Service;import xyz.cc2020.sku.mapper.FileConsumer;import java.io.BufferedReader;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.InputStreamReader;/** * Created by 肖橙橙 * CreateTime 2020-07-27 14:08 * 文件服务类 */public class FileService { /** * 通过URL获取本地内容,调用函数式接口处理 * @param url * @param fileConsumer */ public void fileHandler(String url, FileConsumer fileConsumer) throws Exception { //创建文件读取流 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(url))); //定义一个行变量和内容sb String line; StringBuilder sb = new StringBuilder(); //循环读取文件内容 while ((line = bufferedReader.readLine())!=null){ //如果不为null,则将该行添加 sb.append(line+"\n"); } //调用函数式接口方法,将文件内容传递给lambda表达式 fileConsumer.FileHandler(sb.toString()); }}
第三:编写一个测试类
package xyz.cc2020.sku.Service;import org.junit.Test;/** * Created by 肖橙橙 * CreateTime 2020-07-27 14:24 */public class FileServiceTest { @Test public void fileHandler() throws Exception { //通过lambda表达式打印文件内容 FileService fileService = new FileService(); fileService.fileHandler("填写文件的绝对路径地址",fileContent-> System.out.println(fileContent)); }}
第四:测试成功!
发表评论
最新留言
逛到本站,mark一下
[***.202.152.39]2025年04月12日 17时13分36秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
大规模集群自动化部署工具--Chef的安装部署
2021-05-08
自定义Hive Sql Job分析工具
2021-05-08
【MySQL】(九)触发器
2021-05-08
关于Altium Designer 09导出BOM表不能正确分类问题
2021-05-08
Oracle 11G环境配置
2021-05-08
【Python】(十二)IO 文件处理
2021-05-08
【Oozie】(三)Oozie 使用实战教学,带你快速上手!
2021-05-08
师兄面试遇到这条 SQL 数据分析题,差点含泪而归!
2021-05-08
C语言的数值溢出问题(上)
2021-05-08
BottomNavigationView控件item多于3个时文字不显示
2021-05-08
函数指针的典型应用-计算函数的定积分(矩形法思想)
2021-05-08
8051单片机(STC89C52)以定时器中断模式实现两倒计时器异步计时
2021-05-08
用 wxPython 打印你的 App
2021-05-08
vue项目通过vue.config.js配置文件进行proxy反向代理跨域
2021-05-08
Linux下安装MySql过程
2021-05-08
android:使用audiotrack 类播放wav文件
2021-05-08
vue通过better-scroll 封装自定义的下拉刷新组件
2021-05-08
android解决:使用多线程和Handler同步更新UI
2021-05-08
Element UI 中动态路由的分析及实现
2021-05-08
使用springMVC配置视图管理器后找不到指定的页面
2021-05-08