23,404
社区成员
发帖
与我相关
我的任务
分享
package com.lzw;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class ReadBigFile
{
public static void main(String[] args) throws IOException
{
long start = System.currentTimeMillis();
readFile("test.txt");
long end = System.currentTimeMillis();
System.out.println(end - start);
}
/**
* 比用BufferedReader块4倍左右
*/
public static void readFile(String filePath)
{
int buffSize = 1024;
byte[] bytes = new byte[buffSize];
ByteBuffer byteBuffer = ByteBuffer.allocate(buffSize);
FileChannel channel = null;
try
{
channel = new RandomAccessFile(filePath, "r").getChannel(); //"r" = O_RDONLY
// StringBuffer sb = new StringBuffer(500);
while (channel.read(byteBuffer) != -1)
{
int size = byteBuffer.position();
byteBuffer.rewind();
byteBuffer.get(bytes);
String tmp = new String(bytes, 0, size);
// System.out.print(tmp);
//sb.append(tmp); //使用这个不需要\n,使用StrinbBuffer数据量超大的时候也会内存溢出
byteBuffer.clear();
}
channel.close(); //pls close in finally
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}