java字节流复制文件

时间:2021-10-31 20:57:39
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.junit.Test;

public class JavaIO {

    @Test
    public void test() throws Exception{
        //1、输入输出路径
        String inputPath = "C:\\Users\\zwx474555\\Desktop\\E04D24C1-BB2F-424A-AD2D-7B770C96F9A1.png";  //图片路径
        String outPath = "F:\\123.png";  //复制路径及文件名
        
        //2、输入输出流对象
        FileInputStream fis = new FileInputStream(inputPath);
        FileOutputStream fos = new FileOutputStream(outPath);
        
        //3、声明字节数组,每次按1K读取,按1K输出
        byte[] bytes = new byte[1024];
        
        int temp = 0;
        while((temp = fis.read(bytes)) != -1){
            fos.write(bytes, 0, temp); //一边读取,一边输出
        }
        //4、刷新输出流
        fos.flush();
        
        //5、关闭流
        fis.close();
        fos.close();
        
    }
}