前言
下面是一些 InputStream转String,String转InputStream的方法,大家可以拿去即用
InputStream转String的方法
方法一:
public String inputStreamToString(InputStream inputStream)throws Exception{
byte[] bytes = new byte[0];
int count = 0;
while (count == 0) {
count = inputStream.available();
}
bytes = new byte[count];
inputStream.read(bytes);
String str = new String(bytes);
return str;
}
方法二:
public String inputStream2String(InputStream in) throws IOException {
StringBuffer out = new StringBuffer();
byte[] b = new byte[4096];
for (int n; (n = in.read(b)) != -1;) {
out.append(new String(b, 0, n));
}
return out.toString();
}
方法三:
public String inputStream3String(InputStream inputStream) throws Exception{
StringBuilder sb = new StringBuilder();
String line;
BufferedReader br=null;
String str=null;
try {
br = new BufferedReader(new InputStreamReader(inputStream));
while ((line = br.readLine()) != null) {
sb.append(line);
}
str = sb.toString();
}catch (Exception e){
}finally {
if (br!=null){
br.close();
}
}
return str;
}
注:readLine()是读取流读数据的时候用的,同时会以字符串形式返回这一行的数据,调用一次就会读取一行数据,读取之后会跳到下一行,当读取完所有的数据时会返回null。
方法四:
public String inputStream4String(InputStream inputStream) throws Exception{
String str=null;
try ( ByteArrayOutputStream result = new ByteArrayOutputStream();
){
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
str = result.toString(StandardCharsets.UTF_8.name());
result.close();
}
return str;
}
String转InputStream
InputStrem is = new ByteArrayInputStream(str.getBytes());
或者
ByteArrayInputStream stream= new ByteArrayInputStream(str.getBytes());
我们还可以指定编码
InputStream stream= new ByteArrayInputStream(str.getBytes("UTF-8"));