• Post Reply Bookmark Topic Watch Topic
  • New Topic

Reading a file from a spot other than the beginning

 
Jay George
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey everybody. Given a file, I am trying to read a series of bytes that begin at a place other than the beginning of the file (e.g: I'm trying to read 512 bytes from a 1 MB file starting with the 90th byte). Is there any way to do this without reading in or processing the bytes before it?

I've tried using InputStream's read(byte[] b, int off, int len) method, but I get an IndexOutOfBoundsException whenever the offset is something other than zero.

This is a snippet from the code I have so far:



If I change the offset to zero, I get no exceptions. FYI, the file I am attempting to read from has 19968 bytes.

So is this even possible? Is there a better way to do this other than using FileInputStream? Thanks in advance.
 
Mani Ram
Ranch Hand
Posts: 1140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


The 20 in the above method call, is not the offset inside the input file, rather it's the offset in the specified array (bytesRead).

So, what this code actually does is,
-read 512 bytes (i.e. bytesRead.length), from the input stream, and write into the byte array (i.e. bytesRead), starting from 20th position in that array.

Change it to

and you can see your code working fine (because, the number of bytes read, doesn't exceed the array size).

However, this doesn't solve your actual problem. In order to read from an arbitary position inside a file, you need to use java.io.RandomAccessFile
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!