Java读取文件内容方法比较

最近在做一个语料的清洗程序,需要读取大量的txt文件的内容,然后对内容进行一系列的清洗,这时有两种处理方案,一是用readline()一行一行读取然后拼接起来,二是一次性读取,我倾向于一次性将文本的原始内容直接读取到内存中再做处理,因为涉及的文件量很大,几十、几百G的几十万个文件,这样提升一点速度,整体就能提升很大的速度。当然,这需要你有一台大内存的机器,内存不够者……可以一次读取少部分内容,分多次读取。
读取文件效率最快的方法就是一次全读进来,很多人用readline()之类的方法,可能需要反复访问文件,而且每次readline()都会调用编码转换,再把字符串拼接起来,降低了速度,所以,在已知编码的情况下,按字节流方式先将文件都读入内存,再一次性编码转换是最快的方式,两种情况的代码如下:
readline()方法:

public String getContent(File file){
        StringBuffer sb = new StringBuffer();
        try {
            String encoding="UTF-8";
            if(file.isFile() && file.exists()){ //判断文件是否存在
                InputStreamReader read = new InputStreamReader(
                        new FileInputStream(file),encoding);//考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                while((lineTxt = bufferedReader.readLine()) != null){
                    sb.append(lineTxt);
                }
                read.close();
            }else{
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
        return sb.toString();
   }

字节流一次读取:

public String getContent(File file) throws Exception {
        String encoding="UTF-8";
        byte[] filecontent = {};
        if(file.isFile() && file.exists()){ //判断文件是否存在
            Long filelength = file.length();
            filecontent = new byte[filelength.intValue()];
            FileInputStream in = new FileInputStream(file);
            in.read(filecontent);
            in.close();
        }else{
            System.out.println("找不到指定的文件");
        }
        return new String(filecontent, encoding);
    }
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值