java 实现文件复制

package Gaobo0715_2;
//高博张益桃老师授课

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;
import java.util.Scanner;

public class FileCopy {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("请输入源路径:");
        String srcPath = input.nextLine() ;
        System.out.print("请输入目标路径:");
        String targetPath = input.nextLine();
        System.out.println("正在复制.......");
        copyFile(new File(srcPath), targetPath);
        System.out.println("复制成功......");
    }

    private static void copyFile(File srcFile , String targetPath) {

        String fileName = srcFile.getName();
        File targetFile = new File(targetPath+"/"+fileName);
        if(srcFile.isDirectory()) {//文件夹
            targetFile.mkdirs();
            File[] childFileArr = srcFile.listFiles();
            for (int i = 0; i < childFileArr.length; i++) {
                File childFile = childFileArr[i];
                String childTargetPath = targetFile.getAbsolutePath();
                copyFile(childFile, childTargetPath);
            }
        }else {//文件
            try {
                InputStream is = new FileInputStream(srcFile);
                byte[] bytes = new byte[1024];
                int len = -1 ;

                OutputStream os = new FileOutputStream(targetFile);

                while((len = is.read(bytes))!=-1) {
                    os.write(bytes,0,len);
                }

                os.flush();

                os.close();
                is.close();

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
/*
请输入源路径:D:\PTC-实训教学\扬大两周实习\0713
请输入目标路径:E:\
正在复制.....
复制成功!
*/

你可能感兴趣的:(Java,文件复制)