其他流---字节数组流与文件流对接

时间:2022-07-22
本文章向大家介绍其他流---字节数组流与文件流对接,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

byte[] ----> File

  1. 建立字节读入流 建立字节数组输出流
  2. 建立结果记录byte数组、中间byte数组、长度统计变量len
  3. 刷新流、将流转换到数组中
	public static byte[] getBytesFromFile(String src) throws IOException {
		InputStream is = new BufferedInputStream(new FileInputStream(src));
		ByteArrayOutputStream bos = new ByteArrayOutputStream();

		byte[] dest = null;

		byte[] flush = new byte[1024];
		int len = 0;

		while (-1 != (len = is.read(flush))) {
			bos.write(flush, 0, len);
		}
		bos.flush();
		dest = bos.toByteArray();

		return dest;
	}

File ----> byte[]

1.建立字节数组输入流 建立字节输出流 2. 建立结果记录byte数组、中间byte数组、长度统计变量len 3. 刷新流、将流转换到数组中

	public static void FileFromByteArray(byte[] src, String destPath) throws IOException {
		File dest = new File(destPath);
		InputStream is = new BufferedInputStream(new ByteArrayInputStream(src));
		OutputStream os = new BufferedOutputStream(new FileOutputStream(dest));
		int len = 0;
		byte[] flush = new byte[1024];
		while (-1 != (len = is.read(flush))) {
			os.write(flush, 0, len);
		}
		os.flush();
		os.close();
		is.close();

	}

完整代码如下

package cn.hxh.io.other;

import java.io.*;

public class ByteArrayDemo02 {

	public static void main(String[] args) throws IOException {
		FileFromByteArray(getBytesFromFile("D:/aa/a.txt") , "d:/aa/c.txt");
	}

	public static void FileFromByteArray(byte[] src, String destPath) throws IOException {
		File dest = new File(destPath);
		InputStream is = new BufferedInputStream(new ByteArrayInputStream(src));
		OutputStream os = new BufferedOutputStream(new FileOutputStream(dest));
		int len = 0;
		byte[] flush = new byte[1024];
		while (-1 != (len = is.read(flush))) {
			os.write(flush, 0, len);
		}
		os.flush();
		os.close();
		is.close();

	}

	public static byte[] getBytesFromFile(String src) throws IOException {
		InputStream is = new BufferedInputStream(new FileInputStream(src));
		ByteArrayOutputStream bos = new ByteArrayOutputStream();

		byte[] dest = null;

		byte[] flush = new byte[1024];
		int len = 0;

		while (-1 != (len = is.read(flush))) {
			bos.write(flush, 0, len);
		}
		bos.flush();
		dest = bos.toByteArray();

		return dest;
	}
}