IO流操作三 : 使用字节数组流实现文件的拷贝

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 使用字节数组流实现文件拷贝
 *  1、文件 ---> 字节数组
 *  2、字节数组 ---> 文件
 * @author pence
 * @date 2017年12月28日
 */
public class MyIO3 {

	public static void main(String[] args) throws IOException {

		//从文件获取内容并保存到字节数组
		byte[] data = getBytesFromFile("C:/software/workspace/workspace/Test/src/test/a.txt");
		System.out.println(new String(data,"gbk"));
		
		//将字节数组内容写入文件
		toFileFromByteArray(data, "C:/software/workspace/workspace/Test/src/test/b.txt");
		
	}
	
	/**
	 * 读取字节数组内容输出到文件
	 * @param src
	 * @param destPah
	 * @throws IOException 
	 */
	public static void toFileFromByteArray(byte[] src, String destPath) throws IOException{
		
		//1.创建源
		File dest = new File(destPath);
		
		//2.选择流
		InputStream is = new BufferedInputStream(new ByteArrayInputStream(src));//字节数组输入流
		OutputStream os = new BufferedOutputStream(new FileOutputStream(dest));//文件输出流
		
		//3.操作
		byte[] flash = new byte[1024];
		int len = 0;
		while(-1 != (len=is.read(flash))){
			//输出到文件
			os.write(flash, 0, len);
		}
		os.flush();
		
		//4.关闭流
		os.close();
		is.close();
	}
	
	/**
	 * 读取文件内容并输出到字节数组
	 * @param srcPath
	 * @return
	 * @throws IOException 
	 */
	public static byte[] getBytesFromFile(String srcPath) throws IOException{
		
		//1.创建源
		File src = new File(srcPath); //源文件
		byte[] dest = null; //目标数组
		
		//2.选择流
		InputStream is = new BufferedInputStream(new FileInputStream(src));	//缓冲字节输入流
		ByteArrayOutputStream bos = new ByteArrayOutputStream(); //字节数组输出流
		
		//3.操作
		int len = 0;
		byte[] flash = new byte[1024];
		while(-1 != (len=is.read(flash))){
			//输出到字节数组
			bos.write(flash, 0, len);
		}
		bos.flush();
		//获取数据
		dest = bos.toByteArray(); //此处调用新增方法,故创建对象时不能使用多态
		
		//4.关闭流
		bos.close();
		is.close();
		
		return dest;
	}

}

猜你喜欢

转载自blog.csdn.net/pjz161026/article/details/78927665