-4
\$\begingroup\$

I am currently using this:

Path path = Paths.get("c:\test\test.txt");
byte[] all= Files.readAllBytes(path);

The problem with this is that I have to load the entire file in memory. My requirement is to read the file byte by byte, but in a manner like first 4 bytes mean X, next 16 bytes mean Y and use next 48 bytes for Z, etc.

Right now I am looping through all to do this.. My current code has a pointer which I am moving till all.length and using Arrays.copyOfRange to copy parts to other arrays for use. I am interested in knowing about BufferedReaders which reads a few bytes and then I can process them.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ "My current code has a pointer which I am moving..." - so, show us the code. Too late now that there's an answer, but this question is incomplete. Java does have a great, native solution. \$\endgroup\$ Commented Mar 6, 2016 at 13:16

1 Answer 1

1
\$\begingroup\$

You can use a data input and use the readFully(byte[]...) method.

A quick way would be something like:

byte[] header = new byte[4];
byte[] name = new byte[16];
DataInput input = new DataInputStream(new FileInputStream(file));
input.readFully(header);
input.readFully(name);
input.close();
\$\endgroup\$
2
  • \$\begingroup\$ Thank you for your answer. I have a doubt though. Can you please help me with codereview.stackexchange.com/questions/122037/…? \$\endgroup\$ Commented Mar 6, 2016 at 7:19
  • 1
    \$\begingroup\$ The code above is bound to be a problem. Why not use DataInputStream.readFully() which is the right tool for the job? \$\endgroup\$ Commented Mar 6, 2016 at 13:17

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.