Pergunta

I am working on Bluetooth Application on Android. This inputStream is from connection socket. I want to read bytes upto certain length.

First way I tried :

byte[] data = new byte[lengthtoread];
for (int i = 0; i < data.length; i++)
    data[i] =(byte) mmInStream.read() ;

I have found that it is been too slow.

Sencond way:

   byte[] data = new byte[lengthtoread];
   mmInStream.read(data, 0, lengthtoread);

In this I found that its not reading data completely when length to read is too large

Anyone please help me out ??

Foi útil?

Solução

Using only standard API, the DataInputStream class has a method called readFully that fills a byte array from the stream:

byte[] data = new byte[lengthtoread];
DataInputStream in = new DataInputStream(mmInStream);
in.readFully(data);

Don't forget to close the streams when you are done with them!

Outras dicas

What, exactly, are you trying to do?

If it's to read all the bytes from a file, then do this:

Files.readAllBytes(Paths.get("filename.txt"));

http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#readAllBytes%28java.nio.file.Path%29

Yes: use Jakarta Commons IOUtils. This class contains fully-debugged utility methods for reading and writing streams.

If you want to read the entire stream, use IOUtils.toByteArray(). However, be aware that you might run out of memory when doing this. Usually it's better to process a piece of a stream at a time.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top