Click here to Skip to main content
15,887,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi everybody,
I have an assignment in Java, one of its part is read a byte array from file, start at a specified offset and have a given length.
My solution is using method
Java
read() 
of class
Java
FileInputStream


First, I read all file as an array. Then I copy the sub-array, from specified offset with given length to new array and return the new array.

But, because the memory for a Java application is small, my solution does not work with a 200 MB file.

How c an I read a part of file that I want without reading the whole file?

Thanks for reading my question.
Posted
Comments
Richard MacCutchan 30-Oct-11 4:56am    
Why are you reading the entire file when your instructions specify you to read a fixed length amount from a certain offset? Reading 200Mb in the way you are doing it is not a sensible option.
Sergey Alexandrovich Kryukov 30-Oct-11 19:56pm    
Exactly; as I say, readFully reads array of bytes of required length, from required offset, see my answer.
--SA

1 solution

See: http://download.oracle.com/javase/1.4.2/docs/api/java/io/RandomAccessFile.html#readFully%28byte[],%20int,%20int%29[^], the class is java.io.RandomAccessFile.

[EDIT]

As Richard expressed concern about your familiarity with the concept (or just the terminology) of random access, you can see these articles:
http://en.wikipedia.org/wiki/Random_access[^],
http://en.wikipedia.org/wiki/Random-access_memory[^].

Files also allow random access to any record. Even in the case of disk or even tape memory it's always possible to relocate the reading head to any position. For such devices, this can be very expensive. So, using buffered stream will highly facilitate random-access operations.

—SA
 
Share this answer
 
v2
Comments
Espen Harlinn 30-Oct-11 8:41am    
That more or less solves the assignment :)
Sergey Alexandrovich Kryukov 30-Oct-11 19:56pm    
Thank you, Espen.
--SA
Richard MacCutchan 31-Oct-11 5:39am    
I wonder if OP actually knew about "random access"?
Sergey Alexandrovich Kryukov 31-Oct-11 11:48am    
Thank you, Richard.
Are you not sure OP knew about "random access". As you wish: I added an update to clarify it, please see after [EDIT].
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900