javawaveblogs-20

Friday, October 5, 2007

Parsing Java InputStream To Text and Vice Versa

Here are couple of useful methods to convert from InputStream to String
and vice versa.

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;
}

No comments:

diggthis