[JAVA]字节流拷贝文件

import java.io.*;

public class CopyFile {

    public static void main(String[] args) {
        //1、创建源
        File in = new File("d:/test/1111.mp4");
        File out = new File("d:/test/222.mp4");
        //2、选择流
        InputStream is = null;
        OutputStream os = null;

        try {
            //3、操作数据
            is = new FileInputStream(in);
            os = new FileOutputStream(out);
            byte[] buf = new byte[1024*1024];
            int length = -1;//记录实际读取到的长度
            while ((length = is.read(buf)) != -1) {
                os.write(buf, 0, length);
            }
            os.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {//4、关闭流(先打开的后关闭)
            try {
                if (os != null)
                    os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (is != null)
                    is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/zhengxl5566/p/10360709.html