Reputation: 1
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!!
Upvotes: 0
Views: 113
Reputation: 11
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.
Upvotes: 1
Reputation: 7853
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;
}
Upvotes: 0