Java 中 字节流与Inputstream的互相转换
文章目录
1. File/FileInputStream → byte[]
File -> FileInputStream -> new byte[input.available] -> InputStream.read()
File file = new File("file.txt");
InputStream input = new FileInputStream(file);
byte[] bytes = new byte[input.available()];
input.read(bytes);
2. byte[] → InputStream
new ByteArrayInputStream(bytes);
byte[] bytes = new byte[1024];
InputStream input = new ByteArrayInputStream(bytes);
3. byte[] → File
File -> OutputStram -> BufferedOutputStream -> bufferedOutput.write(bytes);
// bytes = ..... 或 传入一个byte[]
File file = new File('');
OutputStream output = new FileOutputStream(file);
BufferedOutputStream bufferedOutput = new BufferedOutputStream(output);
bufferedOutput.write(bytes);
4. InputStream → OutputStream
使用缓存循环读取InputStream,适用于一些无法直接获取
InputStream.available()
的场景。
public static byte[] getStreamBytes(InputStream is) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
byte[] b = baos.toByteArray();
is.close();
baos.close();
return b;
}