本文主要是介绍【Java】byte数组与流的相互转换,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Java 中 字节流与Inputstream的互相转换
文章目录
- Java 中 字节流与Inputstream的互相转换
- 1. File/FileInputStream → byte[]
- 2. byte[] → InputStream
- 3. byte[] → File
- 4. InputStream → OutputStream
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;
}
这篇关于【Java】byte数组与流的相互转换的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!