2

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 ??

Vinit Siriah
  • 327
  • 3
  • 12
  • how did you realize it(in second approach)? what is the value of `lengthtoread`? what is the target file size? –  Jul 15 '13 at 20:50
  • lengthtoread is large sometimes near about upto 90000 more or less – Vinit Siriah Jul 16 '13 at 18:19
  • so why do you want to read all at a time? it's not a good idea, try to buffer data –  Jul 16 '13 at 18:27
  • what is the reliable size of buffer ?? – Vinit Siriah Jul 16 '13 at 18:32
  • it dependents buddy, it dependents on target environment, you need small in small devices like a J2ME application, but it may be huge in servers, also it dependents on data rate, if data rate is slow, keep buffer small, and for any fetched data do the business, sometimes it dependents to business, for example each task need at least 4096 bytes, I cannot say *how much is good*, it dependents buddy :) –  Jul 16 '13 at 18:48

3 Answers3

4

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!

Joni
  • 108,737
  • 14
  • 143
  • 193
1

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

kittylyst
  • 5,640
  • 2
  • 23
  • 36
0

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.

parsifal
  • 299
  • 1
  • 3