Java中NIO读取文件

import org.apache.commons.lang.StringUtils;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

/**
 * @Author: shuyizhi @Date: 2018-07-30 14:32 @Description: 通过NIO的方式操作文件
 */
public class IODemoByNIO {

    /**
     * InputStream读取文件(按行读取)
     *
     * @param filePath
     */
    public static void readFileByIO(String filePath) {
        if (StringUtils.isEmpty(filePath)) {
            return;
        }
        FileInputStream inputStream = null;
        BufferedReader reader = null;
        try {
            inputStream = new FileInputStream(filePath);
            reader = new BufferedReader(new InputStreamReader(inputStream));
            String str = null;
            int count = 0;
            while ((str = reader.readLine()) != null) {
                // 输出文件内容
                // System.out.println(str);
                count++;
            }
            System.out.println("总共输出: " + count + " 条");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 通过FileChannel从指定的文件中读取数据(按行读取)
     *
     * @param filePath 文件路径
     */
    public static void readFileByChannel(String filePath) {
        if (StringUtils.isEmpty(filePath)) {
            return;
        }
        try {
            List<String> lists = Files.readAllLines(Paths.get(filePath));
            int count = 0;
            for (String str : lists) {
                // 输出文件内容
                // System.out.println(str);
                count++;
            }
            System.out.println("总共输出: " + count + " 条");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值