Pages

Sunday, November 05, 2006

How to convert an InputStream to a String and Back

Input Stream to String:

public String parseISToString(java.io.InputStream is){
java.io.DataInputStream din = new java.io.DataInputStream(is);
StringBuffer sb = new StringBuffer();
try{
String line = null;
while((line=din.readLine()) != null){
sb.append(line+"\n");
}
}catch(Exception ex){
ex.getMessage();
}finally{
try{
is.close();
}catch(Exception ex){}
}
return sb.toString();
}

String to InputStream:

public java.io.InputStream parseStringToIS(String xml){
if(xml==null) return null;
xml = xml.trim();
java.io.InputStream in = null;
try{
in = new java.io.ByteArrayInputStream(xml.getBytes("UTF-8"));
}catch(Exception ex){
}
return in;
}

13 comments :