【Java】byte数组与流的相互转换

Jim.KK 2024-09-06 17:05:02 阅读 78

Java 中 字节流与Inputstream的互相转换

文章目录

Java 中 字节流与Inputstream的互相转换1. File/FileInputStream → byte[]2. byte[] → InputStream3. byte[] → File4. InputStream → OutputStream

1. File/FileInputStream → byte[]

File -> FileInputStream -> new byte[input.available] -> InputStream.read()

<code>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;

}



声明

本文内容仅代表作者观点,或转载于其他网站,本站不以此文作为商业用途
如有涉及侵权,请联系本站进行删除
转载本站原创文章,请注明来源及作者。