Java:InputStream、String、File相互转化
2021-01-06 21:00:56
小记(未测试):
1. String --> InputStream
ByteArrayInputStream stream = new ByteArrayInputStream(str.getBytes());
2. InputStream --> String
String inputStream2String(InputStream is){
BufferedReader in = new BufferedReader(new InputStreamReader(is));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = in.readLine()) != null){
buffer.append(line);
}
return buffer.toString();
}
3. File --> InputStream
InputStream in = new FileInputStream(file);
4. InputStream --> File
public void inputstreamtofile(InputStream ins,File file){
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
5. BufferedImage --> inputStream、BufferedImage --> String
public static InputStream encode(String content, String logoPath, boolean needCompress) throws Exception {
BufferedImage image = QrCodeUtil.createImage(content, logoPath, true);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageIO.write(image, FORMAT, outputStream);
//String streamEncoded = Base64Util.encode(outputStream.toByteArray());
InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
return inputStream;
}