首页 > 技术文章 > 使用字节流复制文件

sun-10387834 2020-08-17 16:10 原文

 1 public static void main(String[] args) throws IOException {
 2         FileInputStream fis = new FileInputStream("c:\\1.jpg");
 3         FileOutputStream fos = new FileOutputStream("d:\\1.jpg");
 4         int len = 0;
 5         byte[] bytes = new byte[1024];
 6         while ((len = fis.read(bytes)) != -1) {
 7             fos.write(Arrays.copyOf(bytes,len));
 8         }
 9         fos.close();
10         fis.close();
11     }

# 注:第7行代码的作用是防止在拷贝的最后一次将bytes数组的1024字节全部拷贝导致复制后的文件略大于源文件。


package stream;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @Classname copy_img
 * @Description TODO
 * @Date 2020/9/30 9:07
 * @Created by Administrator
 */
public class copy_img {
    public static void main(String[] args) {
        copy_file("d://a/8.jpg", "d://a/aa/8.jpg");
    }

    /**
     * 文件复制方法
     * @param sourcepath
     * @param targetpath
     */
    public static void copy_file(String sourcepath, String targetpath) {
        System.out.println("文件开始复制...");
        Long start_time=System.currentTimeMillis();
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(sourcepath);
            fos = new FileOutputStream(targetpath);
            byte[] bytes_in = new byte[1024];
            int len_in = 0;
            while ((len_in = fis.read(bytes_in)) != -1) {
                fos.write(bytes_in, 0, len_in);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fos.close();
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            System.out.println("消耗"+(System.currentTimeMillis()-start_time)+"毫秒,文件复制完毕...");
        }


    }
}

 

推荐阅读