Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java's DataInputStream.readUTF and number of bytes read

Tags:

java

java-me

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!

like image 594
Albus Dumbledore Avatar asked Jul 24 '10 11:07

Albus Dumbledore


People also ask

What is the output data type of DataInputStream ()?

That is why it is called DataInputStream – because it reads data (numbers) instead of just bytes. An application uses a data output stream to write data that can later be read by a data input stream. Data input streams and data output streams represent Unicode strings in a format that is a slight modification of UTF-8.

What is readUTF?

readUTF(DataInput in) Reads from the stream in a representation of a Unicode character string encoded in modified UTF-8 format; this string of characters is then returned as a String .

What is DataInputStream and DataOutputStream in Java?

The DataInputStream class read primitive Java data types from an underlying input stream in a machine-independent way. While the DataOutputStream class write primitive Java data types to an output stream in a portable way. Here is an example to demonstrate the use of DataInputStream and DataOutputStream .

What is the difference between DataInputStream and InputStream?

An inputStream is the base class to read bytes from a stream (network or file). It provides the ability to read bytes from the stream and detect the end of the stream. DataInputStream is a kind of InputStream to read data directly as primitive data types.


1 Answers

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.

like image 74
aioobe Avatar answered Dec 01 '22 09:12

aioobe