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看你了。要是之都就只写r
String 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读写2G以上的大文件(推荐使用以下方法) static String sourceFilePath = "H:\\DataSource-ready\\question.json&qu ...
- java读取大文本文件
原文:http://blog.csdn.net/k21325/article/details/53886160 小文件当然可以直接读取所有,然后放到内存中,但是当文件很大的时候,这个方法就行不通了,内 ...
- java filechannel大文件的读写
java读取大文件 超大文件的几种方法 转自:http://wgslucky.blog.163.com/blog/static/97562532201332324639689/ java 读取一个 ...
- Java读写文本文件操作
package com.test; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; ...
- java处理大文本2G以上
面试中经常碰到类似问题,问题的关键我觉得是用设置一个缓冲区 还有一个思路 是通过Linux split 命令将文件直接切割成小文件,再进行处理再汇总. 或者jdk7提供的 forkjoin 框架,利用 ...
- Java查询大文本
但JAVA本身缺少相应的类库,需要硬编码才能实现结构化文件计算,代码复杂且可读性差,难以实现高效的并行处理. 使用免费的集算器可以弥补这一不足.集算器封装了丰富的结构化文件读写和游标计算函数,书写简单 ...
- java读写文件大全
java读写文件大全 最初java是不支持对文本文件的处理的,为了弥补这个缺憾而引入了Reader和Writer两个类,这两个类都是抽象类,Writer中 write(char[] ch,int o ...
- java读写
IO流下分为字节流与字符流,每个流又分为输入输出以及读写. 字节流的两个基类为InputStream与OutputStream. 字符流为Reader和Writer
- 【Java】大文本字符串滤重的简单方案~
本文章也同步至本人的CSDN博客中: http://blog.csdn.net/u012881584/article/details/70477832 今天来说一个Java中处理大文本字符串虑重的两个 ...
随机推荐
- 负载均衡之Haproxy配置详解(及httpd配置)
下图描述了使用keepalived+Haproxy主从配置来达到能够针对前段流量进行负载均衡到多台后端web1.web2.web3.img1.img2.但是由于haproxy会存在单点故障问题,因此使 ...
- React的CSS
1.代码 <!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="U ...
- Win软件私家珍藏-常用软件工具使用总结
原文:Win软件私家珍藏-常用软件工具使用总结 Windowns常用软件 看图 FastStoneImageViewer 免费软件,好用到爆!没广告!功能齐全!不光能看图,还能修图! Picasa3 ...
- VS2010/MFC编程入门之四(MFC应用程序框架分析)
VS2010/MFC编程入门之四(MFC应用程序框架分析)-软件开发-鸡啄米 http://www.jizhuomi.com/software/145.html 上一讲鸡啄米讲的是VS2010应用 ...
- Android 消息广播Intent传递数据
1.创建布局文件activity_broadcast.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk ...
- SSIS ->> Data Flow Design And Tuning
Requirements: Source and destination system impact Processing time windows and performance Destinati ...
- c语言中argc和argv是什么意思?
argc是参数个数,定义为intargv是字符串数组,存的是参数,定义为char**或者char* argv[]比如你编译好的程序为my.exe在命令行执行 my.exe 1 2 3那argc就是4, ...
- wamp集成环境开启虚拟主机多站点功能
方法/步骤 如果不是全白色,说明没有正常启动,先解决这个情况再进行下一步操作. 我们一键安装wamp到D盘,并可以正常启动,状态如下图所示: 在D:\wamp\bin\apache\Apach ...
- Indoor Positioning System & Real time location system
背景 惨痛的背景,正如我前面提到的,参加了公司的一个训练营.刚进来公司的新人,内心充满着对未来的美好憧憬,期待自己能闯出属于自己的天地.更何况,作为一名程序员,无比的希望所有人对自己写得代码或者App ...
- hdu 4856 Tunnels (bfs + 状压dp)
题目链接 The input contains mutiple testcases. Please process till EOF.For each testcase, the first line ...