JAVA来读取大文本文件
2016-05-06 10:25
375 查看
最近工作中用到文本分析,有的文本足足有好几个G,一次性加载的内存中肯定不合适,所以在读取文件时使用缓冲区来分批读取文件
为了测试,从网盘上把以前破解WIFI密码时用的字典下载了下来,文件有10G,读取时完全没有问题,机器没有出现卡顿现象。
import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; public class ReadBigFile { public static void main(String[] args) throws Exception { readBigTxt(); } private static void readBigTxt() { //原文件路径 String filePath = "E:/BaiduYunDownload/dict.dic"; //输出的文件路径 String outputFile = "E:/BaiduYunDownload/dict2.dic"; File file = new File(filePath); BufferedInputStream bis = null; BufferedReader in = null; FileWriter fw = null; try { bis = new BufferedInputStream(new FileInputStream(file)); //每次读取10M到缓冲区 in = new BufferedReader(new InputStreamReader(bis, "UTF-8"), 10 * 1024 * 1024); //输出的文件 fw = new FileWriter(outputFile); int count = 0; while (in.ready()) { //当count>20000的时候退出循环,只是测试,不需要读取太多行数据 if (count > 20000) { break; } String line = in.readLine(); fw.append(line + "\n"); count++; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (in != null) { in.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if (fw != null) { fw.flush(); fw.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if (bis != null) { bis.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("文件输出完成"); } }
为了测试,从网盘上把以前破解WIFI密码时用的字典下载了下来,文件有10G,读取时完全没有问题,机器没有出现卡顿现象。
相关文章推荐
- Java问题汇总
- Springlake-01 介绍&功能&安装
- Java web 开发环境配置
- Eclipse默认配色的恢复方法
- Spring4 整合 Hibernate3 基本使用(通过注入 SessionFactory)
- 69道Spring面试题和答案
- 69道Spring面试题和答案
- Java 中 List 与 HashSet 的对比
- java.lang.IllegalStateException: commit already called
- Eclipse开发Web常见异常
- Java socket通信
- 解决Eclipse解析不了std::string的方法
- struts2 标签变形和 样式class无效 问题解决方法
- springmvc文件上传下载
- java底层知识(2)--内存知识
- 关于eclipse中ClassNotFoundException:com.mysql.jdbc.Driver的解决办法
- java 文件相关问题
- 如何在 Eclipse 中使用命令行
- Java动态代理实现原理浅析
- java多线程总结