【java】学习路径37-练习:任意文件的复制

Posted on 2022-04-28 13:12  罗芭Remoo  阅读(30)  评论(0编辑  收藏  举报
  • 使用字节完成复制

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

public class Practice01 {
    public static void copyFile(String source , String target) {

        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try{
            fileInputStream = new FileInputStream(source);
            fileOutputStream = new FileOutputStream(target);
            //通过字节去读取
            int data = -1;
            while((data = fileInputStream.read())>=0){
                fileOutputStream.write(data);
            }

        }catch(IOException ioException){
            ioException.printStackTrace();
        }finally{
            try {
                fileInputStream.close();
            }catch(IOException ioException){
                ioException.printStackTrace();
            }
            try{
                fileOutputStream.close();
            }catch(IOException ioException){
                ioException.printStackTrace();
            }
        }

    }
}

  • 使用字节数组完成复制
public static void copyFileByArray(String source , String target) {

    FileInputStream fileInputStream = null;
    FileOutputStream fileOutputStream = null;
    try{
        fileInputStream = new FileInputStream(source);
        fileOutputStream = new FileOutputStream(target);
        //通过字节去读取
        byte[] dataArray = new byte[1024];
        int length = -1;
        while((length = fileInputStream.read(dataArray))>=0){
            fileOutputStream.write(dataArray,0,length);
        }

    }catch(IOException ioException){
        ioException.printStackTrace();
    }finally{
        try {
            fileInputStream.close();
        }catch(IOException ioException){
            ioException.printStackTrace();
        }
        try{
            fileOutputStream.close();
        }catch(IOException ioException){
            ioException.printStackTrace();
        }
    }

}