当前位置:Gxlcms > 数据库问题 > java中利用RandomAccessFile读取超大文件

java中利用RandomAccessFile读取超大文件

时间:2021-07-01 10:21:17 帮助过:2人阅读

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

 

java中利用RandomAccessFile读取超大文件

标签:

人气教程排行