Java读取和操作大数据文本数据

在处理文本时,经常遇到超过1g存储的数据,直接简单的读取,可能遇到java空间不足的问题,为解决此问题,可将大文本数据按照行进行切分为很多块,并将每一块存储为一个文本

 
  1. public class BigDataRead {
  2. public static void main(String[] args) throws IOException {
  3. long timer = System.currentTimeMillis();
  4. int bufferSize = 20 * 1024 * 1024;//设读取文件的缓存为20MB
  5. //建立缓冲文本输入流
  6. File file = new File("I:/qianyang/预测数据/user_contentdetection_qianyang");
  7. FileInputStream fileInputStream = new FileInputStream(file);
  8. BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
  9. //注意这里有时会乱码,根据自己的文本存储格式,进行调整
  10. InputStreamReader inputStreamReader = new InputStreamReader(bufferedInputStream,"utf-8");
  11. BufferedReader input = new BufferedReader(inputStreamReader, bufferSize);
  12. //要分割的块数减一,这里表示分割为31个文件
  13. int splitNum = 30;
  14. //12046表示我的输入本文的行数,我的文本12046行,由于每行文本较长,所有存储占用较大
  15. int fileLines = 12046;
  16. //分割后存储每个块的行数
  17. long perSplitLines = fileLines / splitNum;
  18. for (int i = 0; i <= splitNum; ++i){
  19. //分割
  20. //每个块建立一个输出
  21. BufferedWriter output = new BufferedWriter( new OutputStreamWriter( new FileOutputStream( new File("I:/qianyang/预测数据/分块/part" + i + ".txt")),"gbk"));
  22. String line = null;
  23. //逐行读取,逐行输出
  24. for (long lineCounter = 0; lineCounter < perSplitLines && (line = input.readLine()) != null; ++lineCounter)
  25. {
  26. output.append(line + "\r");
  27. }
  28. output.flush();
  29. output.close();
  30. output = null;
  31. }
  32. input.close();
  33. timer = System.currentTimeMillis() - timer;
  34. //我的1.6g数据不要1分钟,分割完毕
  35. System.out.println("处理时间:" + timer);
  36. }
  37. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值