Java中超大文件读写
如果文件过大不能一次加载,就可以利用缓冲区:
File file = new File(filepath); BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file)); BufferedReader reader = new BufferedReader(new InputStreamReader(fis,"utf-8"),10*1024*1024);// 用10M的缓冲读取文本文件 String line = ""; while((line = reader.readLine()) != null){ //TODO: write your business }
还可以用RandomAccessFile类读取,进行分段批操作:
String path = "你要读的文件的路径"; RandomAccessFile br = new RandomAccessFile(path, "rw"); 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();