Java读写大文本文件(2GB以上)
如下的程序,将一个行数为fileLines的文本文件平均分为splitNum个小文本文件,其中换行符'r'是linux上的,windows的java换行符是'\r\n':
package kddcup2012.task2.FileSystem; 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 FileSplit { public static void main(String[] args) throws IOException { long timer = System.currentTimeMillis(); int bufferSize = 20 * 1024 * 1024;//设读取文件的缓存为20MB //建立缓冲文本输入流 File file = new File("/media/Data/毕业设计/kdd cup/数据/userid_profile.txt"); FileInputStream fileInputStream = new FileInputStream(file); BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream); InputStreamReader inputStreamReader = new InputStreamReader(bufferedInputStream); BufferedReader input = new BufferedReader(inputStreamReader, bufferSize); int splitNum = 112-1;//要分割的块数减一 int fileLines = 23669283;//输入文件的行数 long perSplitLines = fileLines / splitNum;//每个块的行数 for (int i = 0; i <= splitNum; ++i) { //分割 //每个块建立一个输出 FileWriter output = new FileWriter("/home/haoqiong/part" + i + ".txt"); String line = null; //逐行读取,逐行输出 for (long lineCounter = 0; lineCounter < perSplitLines && (line = input.readLine()) != null; ++lineCounter) { output.append(line + "\r"); } output.flush(); output.close(); output = null; } input.close(); timer = System.currentTimeMillis() - timer; System.out.println("处理时间:" + timer); } }
以上程序处理大文本文件只需要30MB左右的内存空间(这和所设的读取缓冲大小有关),但是速度不是很快,在磁盘没有其他程序占用的情况下,将200MB文件分割为112份需要20秒(机器配置:Centrino2 P7450 CPU,2GB DDR3内存,Ubuntu 11.10系统,硬盘最大读写速度大约60MB/S)。
另外,对于几百兆到2GB大小的文件,使用内存映射文件的话,速度会块一些,但是内存映射由于映射的文件长度不能超过java中int类型的最大值,所以只能处理2GB以下的文件。
package helloword.helloword;import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel;public class ReadBig {public static String fff = "C:\\mq\\read\\from.xml";public static void main1(String[] args) throws Exception {final int BUFFER_SIZE = 0x300000;// 缓冲区大小为3M File f = new File(fff);MappedByteBuffer inputBuffer = new RandomAccessFile(f, "r").getChannel().map(FileChannel.MapMode.READ_ONLY,f.length() / 2, f.length() / 2);byte[] dst = new byte[BUFFER_SIZE];// 每次读出3M的内容long start = System.currentTimeMillis();for (int offset = 0; offset < inputBuffer.capacity(); offset += BUFFER_SIZE) {if (inputBuffer.capacity() - offset >= BUFFER_SIZE) {for (int i = 0; i < BUFFER_SIZE; i++)dst[i] = inputBuffer.get(offset + i);} else {for (int i = 0; i < inputBuffer.capacity() - offset; i++)dst[i] = inputBuffer.get(offset + i);}int length = (inputBuffer.capacity() % BUFFER_SIZE == 0) ? BUFFER_SIZE: inputBuffer.capacity() % BUFFER_SIZE;System.out.println(new String(dst, 0, length));// new// String(dst,0,length)这样可以取出缓存保存的字符串,可以对其进行操作 }long end = System.currentTimeMillis();System.out.println("读取文件文件一半内容花费:" + (end - start) + "毫秒");}public static void main2(String[] args) throws Exception {int bufSize = 1024;byte[] bs = new byte[bufSize];ByteBuffer byteBuf = ByteBuffer.allocate(1024);FileChannel channel = new RandomAccessFile(fff, "r").getChannel();while (channel.read(byteBuf) != -1) {int size = byteBuf.position();byteBuf.rewind();byteBuf.get(bs); // 把文件当字符串处理,直接打印做为一个例子。System.out.print(new String(bs, 0, size));byteBuf.clear();}}public static void main3(String[] args) throws Exception {BufferedReader br = new BufferedReader(new FileReader(fff));String line = null;while ((line = br.readLine()) != null) {System.out.println(line);}}public static void main(String[] args) throws Exception {int bufSize = 1024;byte[] bs = new byte[bufSize];ByteBuffer byteBuf = ByteBuffer.allocate(1024);FileChannel channel = new RandomAccessFile("d:\\filename", "r").getChannel();while (channel.read(byteBuf) != -1) {int size = byteBuf.position();byteBuf.rewind();byteBuf.get(bs);// 把文件当字符串处理,直接打印做为一个例子。System.out.print(new String(bs, 0, size));byteBuf.clear();}}}
package helloword.helloword;import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.RandomAccessFile; import java.util.Scanner;public class TestPrint {public static void main(String[] args) throws IOException {String path = "你要读的文件的路径";RandomAccessFile br = new RandomAccessFile(path, "rw");// 这里rw看你了。要是之都就只写rString str = null, app = null;int i = 0;while ((str = br.readLine()) != null) {i++;app = app + str;if (i >= 100) {// 假设读取100行i = 0;// 这里你先对这100行操作,然后继续读app = null;}}br.close();}// 当逐行读写大于2G的文本文件时推荐使用以下代码void largeFileIO(String inputFile, String outputFile) {try {BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File(inputFile)));BufferedReader in = new BufferedReader(new InputStreamReader(bis, "utf-8"), 10 * 1024 * 1024);// 10M缓存FileWriter fw = new FileWriter(outputFile);while (in.ready()) {String line = in.readLine();fw.append(line + " ");}in.close();fw.flush();fw.close();} catch (IOException ex) {ex.printStackTrace();}} }
File file = new File(filepath); BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file)); BufferedReader reader = new BufferedReader(new InputStreamReader(fis,"utf-8"),5*1024*1024);// 用5M的缓冲读取文本文件 String line = ""; while((line = reader.readLine()) != null){ //TODO: write your business }
Java读写大文本文件(2GB以上)相关推荐
- Java查询大文本文件的处理方法
有时我们需要查询大文本而不是数据库,这时就需要流式读入文件并实现查询算法,还要进行并行处理以提高性能.但JAVA本身缺少相应的类库,需要硬编码才能实现结构化文件计算,代码复杂且可读性差,难以实现高效的 ...
- python 生成nc文件_Python生成器处理大文本文件的代码
运维经常要读写大文本文件,几个G用生成器读写,速度很快. 几十G的先切分为N个小文件,再处理. # coding:utf-8 """ 黄哥python远程视频培训班 ht ...
- JAVA之NIO按行读写大文件,完美解决中文乱码问题
JAVA之NIO按行读写大文件,完美解决中文乱码问题 参考文章: (1)JAVA之NIO按行读写大文件,完美解决中文乱码问题 (2)https://www.cnblogs.com/jpfss/p/89 ...
- 大三、研二的秋招备战路线(Java、大数据)
本文经授权转载自微信公众号:大数据肌肉猿 一.写作背景 二.秋招的意义 三.不同水平的同学备战秋招的策略(案例) 四.部分面试题整理 五.准备过程中的注意事项 六.针对简历复习 一.写作背景 1.分享 ...
- Java知识大全 - 十二、Java和大数据
Java 是大数据处理中使用最广泛的编程语言之一,因为它的性能.可扩展性和易用性.Java有几个库和框架为大数据处理提供支持,包括Apache Hadoop,Apache Spark,Apache S ...
- java读写json格式的文件方法详解.txt,并批量存储进redis
捐躯赴国难,视死忽如归.恸哭六军俱缟素,冲冠一怒为红颜.君子坦荡荡,小人长戚戚.风日晴和人意好,夕阳箫鼓几船归.民为贵,社稷次之,君为轻.Java 读写json格式的文件方法详解 文章录入:7747. ...
- 杂记一:rocksdb架构及其java读写api
1.架构 Rocksdb中引入了ColumnFamily(列族, CF)的概念,所谓列族也就是一系列kv组成的数据集.所有的读写操作都需要先指定列族. 写操作先预写日志(Write-Ahead Log ...
- ASP 如何读写一个文本文件
利用Active Server Pages脚本,你就几乎完全可以控制服务器的文件系统.需要如下的组件: ■FileSystemObject:这个对象包括了一些基本的对文件系统进行操作的方法,比如说,复 ...
- java实现大文件分片上传
java实现大文件分片上传 在项目中用到了大文件上传功能,最初从网上参考了一些代码来实现,但是最终的上传效果不是很好,速度比较慢. 之前的上传思路是: 前端利用webUploader分片大文件 后端接 ...
最新文章
- 零售行业O2O盛行 或成黑客窃取数据目标
- JavaWeb总结(六)—Session
- Eclipse内存分析工具的用法
- c++ array 模板类使用
- eeprom stm8l 擦除 读写_[STM8L]EEPROM操作读与写
- Netty ChannelOption 解释
- python在线考试系统设计csdn下载_一种通用的网页相似度检测算法
- 推荐SQL Server Management Studio以及Visual Studio下的免费的插件 ApexSQL Complete
- LS-DYNA 学习总结与感悟 以EM模块为主
- 苗木损耗1.1用计算机怎么算,04园林绿化定额说明
- 远程无人值守批量装机(图文详解)
- 颈椎病的康复锻炼方法
- linux生成checksum,SF2281修改Lic授权ID生成新checksum生成器
- CentOS 7安装Mongodb并使用Robo 3T远程测试连接
- FPGA(一)Vivado与ModelSim
- 天气预报地区id列表
- 用Python破解WiFi密码,亲测有效,简直不能太爽了
- 程序员如何摆脱35岁技术泥潭?
- 360极速浏览器显示https证书无效解决方法
- 激光雷达和3D点云算法
热门文章
- android7.1 shotcuts,Android N App Shotcuts 学习
- element表格固定某一行_WPS表格快捷键讲解大全1(区域选取)!
- 80端口被占用了怎么办_如何查看端口占用情况
- 服务号idbase64_微信公众号-上传图片顺便转base64
- while0表示什么意思_轮胎上的各种字符都表示什么意思,家用车的轮胎又该如何选择呢?...
- android 动态控制截屏,应用助手for Android新版本:可动态截屏存图
- linux查看文件列表内存地址ll,linux指令之文件查看 ls
- html表单提交前验证,jquery表单提交前实现同步验证(附代码)
- django批量修改table_Django 数据库表多对多的创建和增删改查
- 苹果cms10的php.ini目录列表,[苹果cmsV10]常见问题整理官方版