逐行读取txt文本并将结果返回到List<String>

public static List read(String filePath){
        BufferedReader br = null;
        List<String> strings = new ArrayList();
        String line = null;
        try {
            //根据文件路径创建缓冲输入流
            br = new BufferedReader(new FileReader(filePath));
            String str = "";

            //循环读取文件的每一行,对需要修改的行进行修改,放入缓冲对象中
            while ((line = br.readLine()) != null) {
                //设置正则将多余空格都转为一个空格
                str = line;
                strings.add(str);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (br != null) {// 关闭流
                try {
                    br.close();
                } catch (IOException e) {
                    br = null;
                }
            }
        }
        return strings;
    }

测试:

public class Test {

    public static void main(String[] args) {

        //读入文件
        String filePath = "xxx.txt"; // 文件路径
        List<String> lists = read(filePath);
        System.out.println(lists);
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值