java使用IO字节流读取复制文件

版权声明:[email protected] https://blog.csdn.net/weixin_43198122/article/details/84865521

具体代码如下:

package com.copy;

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

public class reviewio {
	public static byte[]  FileToBytearr(String src) throws Exception{
		File src1=new File(src);
		InputStream is = new FileInputStream(src1);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int len=-1;
		byte[] datas=new byte[2048];
		while((len=is.read(datas))!=-1){
			baos.write(datas, 0, len);
		}
		baos.flush();
		baos.close();
		is.close();
		return baos.toByteArray();
	}
	public static void ByteArrToFile(String src,byte[] b) throws Exception{
		File src1=new File(src);
		ByteArrayInputStream bais = new ByteArrayInputStream(b);
		OutputStream os=new FileOutputStream(src1);
		int len=-1;
		byte[] c=new byte[1024];
		while((len=bais.read(c))!=-1){
			os.write(c, 0, len);
		}os.flush();
		bais.close();
		os.close();
	}
	public static void main(String[] args) throws Exception {
		byte[] a=FileToBytearr("C:/Users/17331/Desktop/poetry.html");//你要复制的文件的路径
		System.out.println(a.length);
		ByteArrToFile("C:/Users/17331/Desktop/poetry1.html",a);//你要复制文件到什么地方的路径
	}

}

猜你喜欢

转载自blog.csdn.net/weixin_43198122/article/details/84865521