Java大文件读取

来源:互联网 发布:济南行知小学是公立 编辑:程序博客网 时间:2024/05/17 08:02

1.使用RandomAccess读取

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();
}

}
2.使用BufferReader设置缓冲区大小
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();
        }







0 0