java 讀取一個巨大的文本文件既能保證內存不溢出又能保證性能
2010-09-25 11:18:50| 分類: 默認分類 |字號 訂閱
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);
/**
*
* map(FileChannel.MapMode mode,long position, long size)
*
* mode - 根據是按只讀、讀取/寫入或專用(寫入時拷貝)來映射文件,分別爲 FileChannel.MapMode 類中所定義的
* READ_ONLY、READ_WRITE 或 PRIVATE 之一
*
* position - 文件中的位置,映射區域今後位置開始;必須爲非負數
*
* size - 要映射的區域大小;必須爲非負數且不大於 Integer.MAX_VALUE
*
* 因此若想讀取文件後半部份內容,如例子所寫;若想讀取文本後1/8內容,須要這樣寫map(FileChannel.MapMode.READ_ONLY,
* f.length()*7/8,f.length()/8)
*
* 想讀取文件全部內容,須要這樣寫map(FileChannel.MapMode.READ_ONLY, 0,f.length())
*
*/
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 main(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();
}
}
}
java 讀取大容量文件,內存溢出?怎麼按幾行讀取,讀取屢次。 2011-7-8 11:05 提問者:仙劍奇俠傳__五 | 懸賞分:10 | 瀏覽次數:433次
2011-7-8 11:35 最佳答案 import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
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();
}
jdk自己就支持超大文件的讀寫。
網上的文章基本分爲兩大類,一類是使用BufferedReader類讀寫超大文件;另外一類是使用RandomAccessFile類讀取,通過比較,最後使用了前一種方式進行超大文件的讀取,下面是相關代碼,其實很簡單
-------------------------------------------------------------------
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
}
---------------------------------------------------------------------
注意代碼,在實例化BufferedReader時,增長一個分配緩存的參數便可