字符串转换成流
public InputStream getInputStream(String str) {
if (str != null && !"".equals(str.trim())) {
try {
ByteArrayInputStream inputStream = new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8));
return inputStream;
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
流转换成字符串
方式1
public String getStringByInputStream(InputStream inputStream) {
if (inputStream != null) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
String text = "";
while ((text = reader.readLine()) != null) {
sb.append(text);
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
方式2
public static String getStringByInputStream(InputStream inputStream) {
if (inputStream != null) {
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int length = 0;
byte[] bytes = new byte[1024];
while ((length = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, length);
}
inputStream.close();
outputStream.close();
return outputStream.toString();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}