1.InputStream转String
/*
* InputStream转字符串
*/
public String inputstrToStr(InputStream inputStream) throws IOException {
byte[] bytes = new byte[0];
bytes = new byte[inputStream.available()];
// 读取文件内容到字节数组
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead = inputStream.read(bytes, offset, bytes.length - offset)) >= 0) {
offset += numRead;
}
// 读取完毕的校验
if (offset < bytes.length) {
throw new IOException("不能完全讀取文件");
}
inputStream.close();
String encodedFileString = Base64.getEncoder().encodeToString(bytes);
return encodedFileString;
}
2.String转InputStream
/*
* 字符串转InputStream
*/
public InputStream str2Inputstr(String inStr) {
try {
byte[] bytes = Base64.getDecoder().decode(inStr);
return new ByteArrayInputStream(bytes);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}