Saturday, July 14, 2012

Reading Bytes from InputStream

To develop blackberry application we continues need to reading file and communication to socket server. Today we study simple utility to reading bytes from input stream. Because inputstream use to read data from file as well as socket(TCP) connection.

Here we believe that "in" is Inputstream variable.

1. Read fully inputstream from file:

long dataLength = is.available();// here we get length of readable data on inputstream

byte[] bytes = new byte[(int) dataLength];
is.read(bytes);
String fileData = new String(bytes);
System.out.println(fileData);
This example we can't read socket inputstream. Following example use to read socket inputstream.

2. Read fully inputstream form TCP/Socket connection:

public byte[] getBytesFromInputStream(InputStream is){ 
 try{
 byte[] bytes = null;
  try {
    int dataLength = input.readInt();
    System.out.println("Read Data: "+dataLength);
    bytes = new byte[dataLength];
    int totalRead = 0;
    while(totalRead < dataLength){
      int read = input.read(bytes,totalRead,dataLength-totalRead);
      totalRead+=read;
    }
 System.out.println("Size of Byte Array: "+bytes.length +" Data "+bytes);
 }catch (Exception e) {
    System.out.println(">>>>>>>" + e);
 }
 return bytes;
}
Hope helpfull..

No comments:

Post a Comment