convertion between InputStream & String 1. String --> InputStream
InputStream convertToInputStream(String str)
{
ByteArrayInputStream is = new ByteArrayInputStream(str.getBytes());
return is;
}
2. InputStream --> String
String convertToString(InputStream is)
{
BufferedReader in = new BufferedReader(new InputStreamReader(is));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = in.readLine()) != null)
{
buffer.append(line);
}
return buffer.toString();
}
When I do the socket programming, I always need to deal with inputstream and string, above are the basic ways to so that, but I am not sure if there are any simpler ways to do that...
-----------------------------------------------------------------------------
public static String string2Blob(String str) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
buffer.append(Integer.toHexString( (int) str.charAt(i)));
}
return buffer.toString();
}
public static String blob2String(String blob) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < blob.length() - 1; i += 2) {
int iByte = Integer.parseInt(blob.substring(i, i + 2), 16);
sb.append( (char) iByte);
}
return sb.toString();
}