超大文件我們使用普通的文件讀取方式都很慢很卡,在java中為我提供了RandomAccessFile函數,可以快速的讀取超大文件並且不會感覺到卡哦,下面看我的一個演示實例。
服務器的日志文件往往達到400多M,簡單的文件讀取實在太慢,太占用機器資源。
特別是如果你需要5分鍾就掃描一次日志文件,來統計一些即時數據。比如剛才10分鍾的來訪客戶(大型網站用戶統計系統例如51.la 會經常用到吧。)即時掃描大數據文件中的一部分顯得非常之重要。
本文講述了如果使用java的RandomAccessFile方法從一個很大的文件來讀取部分字節
測試文件總大小46085個字節
讀取文件最后85個字節
文件大小:46085
85
測試效果
擴展功能 —> 優酷視頻
其他的如奇藝,土豆之類操作順序相同。當然我們也可以讀取從46000只讀取20個字節,看個人需要,這里僅僅作為示例
package com.javaer.examples.file; import java.io.IOException; import java.io.RandomAccessFile; public class ReadBigFile { public static void readBigFile() throws IOException{ String fileName = "/Users/mc2/Desktop/youku.txt"; RandomAccessFile randomFile = null; randomFile = new RandomAccessFile(fileName, "r"); long fileLength = randomFile.length(); System.out.println("文件大小:" + fileLength); int start = 46000; randomFile.seek(start); byte[] bytes = new byte[91]; int byteread = 0; // 一次讀10個字節,如果文件內容不足10個字節,則讀剩下的字節。 // 將一次讀取的字節數賦給byteread while ((byteread = randomFile.read(bytes)) != -1) { // System.out.write(bytes, 0, byteread); } System.out.println(bytes.length); System.out.println(new String(bytes,"UTF-8")); if (randomFile != null) { randomFile.close(); } } /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { ReadBigFile.readBigFile(); } }
即使很大的文件,從里面讀取一點數據,速度也很快。全部讀取出來,也會占用很少的內存。
核心提示: randomFile.seek(start);
跳躍讀取,從這里開始讀。指針直接指到start這個位置開始讀取文件。
bytes獲取可以作如下替換,不同場合,不同使用
byte[] bytes = new byte[91]; int byteread = 0; // 一次讀10個字節,如果文件內容不足10個字節,則讀剩下的字節。 // 將一次讀取的字節數賦給byteread while ((byteread = randomFile.read(bytes)) != -1) { // System.out.write(bytes, 0, byteread); } System.out.println(bytes.length);byte[] bytes ; int byteread = 0; ByteArrayOutputStream byteout = new ByteArrayOutputStream(); byte tmp[] = new byte[1024]; byte context[]; int i = 0; int has=0; while ((i = randomFile.read(tmp)) != -1) { byteout.write(tmp, 0, i); has +=i; if(has > 10240) break; } bytes = byteout.toByteArray();