简体   繁体   中英

how to read particular amount of data from a file in java

I have a large file of 45MB, and suppose the memory available to me is limited and I want to read 5MB first and so on.

I need to do this using Java. Somebody please help me out.

Thanks in advance!!

I think you can just use basic byte streams for this. Check out http://docs.oracle.com/javase/tutorial/essential/io/bytestreams.html

I'd use the read(byte[] b) method of a FileInputStream class which 'Reads up to b.length bytes of data from this input stream into an array of bytes'

read(byte[] b, int off, int len) method would also allow you to do this with an offset for previously read data.

Following code would read 5000 bytes (5MB) from the file.

byte[] bytes = new byte[5000]; 
    DataInputStream dis = new DataInputStream(new FileInputStream(file)); 
      int read = 0;
      int numRead = 0;
      while (read < bytes.length && (numRead=dis.read(bytes, read, bytes.length-read)) >= 0) {
        read = read + numRead;
      }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM