【六袆-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));    }}

第四:测试成功!

 

 

 

 

 

上一篇:【六袆-Java】@Param属性的用法
下一篇:【六袆-Mysql】insert新增数据,并获取主键 selectKey的说明

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2025年04月12日 17时13分36秒