liamzebedee
liamzebedee

Reputation: 14490

Does Java save the read position in the InputStream?

I'm in the process of reading data, does Java 'save' your bytes read, or do I have to use an offset?

Upvotes: 0

Views: 3637

Answers (3)

Peter Lawrey
Peter Lawrey

Reputation: 533530

You just to mirror @WhiteFang's solution for writing.

FileInputStream fis = new FileInputStream(files[0]);
DataInputStream dis = new DataInputStream(new BufferedInputStream(fis));
int numFiles = dis.readInt();
int numBytesInName = dis.readInt();
String filename = dis.readUTF();
long numBytesInFile = dis.readLong();
// loop to read bytes into a byte[]

BTW, using writeUTF/readUTF makes writing the length of the file name redundant. Additionally, you don't need to record the number of files if you are not going to write anything after this information.

Upvotes: 2

user372743
user372743

Reputation:

A FileInputStream does indeed save your position.

If you have a file with 3 bytes, 0xff 0x00 0x0c, calling:

System.out.println(fis.read());
System.out.println(fis.read());
System.out.println(fis.read());

Will output:

255
0
12

Upvotes: 3

Related Questions