java - Get bytes from the Int returned from socket intputStream read() -


i have inputstream , want read each char until find comma "," socket.

heres code

private static packet readpacket(inputstream is) throws exception {     int ch;     packet p = new packet();      string type = "";     while((ch = is.read()) != 44) //44 "," in iso-8859-1 codification     {         if(ch == -1)             throw new ioexception("eof");         type += new string(ch, "iso-8859-1"); //<----does not compile     }     ... } 

string constructor not receive int, array of bytes. read documentation , says

read(): reads next byte of data input stream.

how can convert int byte ? using less significant bits (8 bits) of 32 bits of int ?

since im working java, want keep full plataform compatible (little endian vs big endian, etc...) whats best approach here , why ?

ps: dont want use ready-to-use classes datainputstream, etc....

the string constructor takes char[] (an array)

type += new string(new byte[] { (byte) ch }, "iso-8859-1"); 

btw. more elegant use stringbuilder type , make use of append-methods. faster , shows intend better:

private static packet readpacket(inputstream is) throws exception {     int ch;     packet p = new packet();      stringbuilder type = new stringbuilder();     while((ch = is.read()) != 44) {         if(ch == -1)             throw new ioexception("eof");         // note: conversion byte char here iffy, works iso8859-1/us-ascii         // fails horribly utf etc.         type.append((char) ch);     }     string data = type.tostring();     ... } 

also, make more flexible (e.g. work other character encodings), method better take inputstreamreader handles conversion bytes characters (take @ inputstreamreader(inputstream, charset) constructor's javadoc).


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -