您的位置:首页 > 其它

String与InputStream相互转换

2016-07-07 11:03 375 查看
1.String to InputStream

public static InputStream String2InputStream(String name) {
return new ByteArrayInputStream(name.getBytes());
}


2.InputStream to String

这里提供几个方法。

public static String InputStream2String(InputStream input,String encode) throws IOException {
StringBuilder builder = new StringBuilder();

InputStreamReader reader = new InputStreamReader(input,encode);
BufferedReader bufferedReader = new BufferedReader(reader);
String line = null;
try {
while ((line = bufferedReader.readLine()) != null) {
builder.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
input.close();
}
return builder.toString();
}

public static String InputStream2String2(InputStream input) throws IOException {
StringBuffer buffer = new StringBuffer();
byte[] b = new byte[1024];
int n;
try {
while ((n = input.read(b)) != -1) {
buffer.append(new String(b, 0, n));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
input.close();
}
return buffer.toString();
}

public static String InputStream2String3(InputStream input) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int i;
try {
while ((i = input.read()) != -1) {
outputStream.write(i);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
input.close();
}
return outputStream.toString();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: