欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-04-24 11:33:42
...

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

相关标签: # IO流技术