tags:

views:

121

answers:

2

Hi there!

I am writing a custom archive format in JAVA (J2ME to be precise). The archiver works OK, however I have little problems with de-archiving.

How could I know how many bytes have been read when reading a UTF8 string thorough the readUTF method? I know that the first two bytes of a string saved using writeUTF are a short value of the string's length, but I'd like a nicer solution.

Or is there any way to know how many bytes are left till the end of the DataInputStream (the available method doesn't seem to return meaningful values). The stream was opened by a FileConnection, i.e. FileConnection.openDataInputStream.

Thanks guys!

A: 

The available() method returns what it is documented to return, which isn't what you are trying to use it for. See the Javadoc.

You could write your own byte-counting FilterInputStream and put it between the data input stream and the underlying stream. But you'll have to get the total byte count of the source from the source, that information isn't available to any input stream.

EJP
AFAIK, FilterInputStream is not available on the MID Profile.
aioobe
Doesn't really matter, you can write it all yourself just as easily.
EJP
Also do you really need these byte counts? You will get EOF indications when you get to the end of the stream ...
EJP
@EJP, I know what the documentation says about `available()`.Easiest way will be to rewrite the structure of the archive format. Now it is like that archive_header, (file_header, content)*I'll just put the headers at one place in the end. Anyway, my asking was regarding the fact that it's strange that there is no "official" way of getting to know how many actual bytes have been read. Thank you all!
Albus Dumbledore
+1  A: 

I can't see a way of achieving this using the CLDC API directly. A simple solution however, would be to roll your own "CountingInputStream" that extends InputStream and counts the number of bytes read. You would basically just need to override the three read-methods.

The file size is available through the FileConnection.

aioobe
I know about the `fileSize()`. I agree about `CountingInputStream`, but this looks ugly (at least to me).
Albus Dumbledore
I see your point, but I don't think it's that ugly. Such a class is fairly useful and definitely reusable, also in other situations than for FileConnections. And even if it is slightly ugly, it's encapsulated and stowed away in a small class.
aioobe