java 实现Linux中的cp命令

import java.io.*;
import java.util.Scanner;
public class cp {
    public  static void copyFolder(File fileold , File filenew) {
        if(fileold.isDirectory()){
            File temp=new File(filenew,fileold.getName());
            temp.mkdirs();
            for (File file : fileold.listFiles()) {
                copyFolder(file,temp);
            }
        }else{
            copyFile(fileold,new File(filenew,fileold.getName()));
        }
    }
    public static void copyFile(File strOldpath, File strNewPath) {
            InputStream inputStream =null;
            FileOutputStream fileOutputStream =null;
        try {
           // File fOldFile = new File(strOldpath);
            if (strOldpath.exists()) {
                int bytesum = 0;
                int byteread = 0;
                 inputStream = new FileInputStream(strOldpath);
                fileOutputStream = new FileOutputStream(strNewPath);
                byte[] buffer = new byte[1024];
                while ((byteread = inputStream.read(buffer)) != -1) {
                    bytesum += byteread; //这一行是记录文件大小的,可以删去
                    fileOutputStream.write(buffer, 0, byteread);
                    //三个参数,第一个参数是写的内容,
                    //第二个参数是从什么地方开始写,第三个参数是需要写的大小
                }
               // inputStream.close();
                // fileOutputStream.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("复制单个文件出错");
            e.printStackTrace();
        }finally {
            if(inputStream!=null)
            {
                try{
                    inputStream.close();
                }catch (IOException e2)
                {
                    e2.printStackTrace();
                }
            }
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e3) {
                    e3.printStackTrace();
                }
            }
        }
    }
    public static void main(String args[]) {
        Scanner input=new Scanner(System.in);
        System.out.println("请输入旧的路径:");
        String oldpath = input.next();
        File  f1 = new File(oldpath);
        System.out.println("请输入新的路径");
        String newpath = input.next();
        File f2 = new File(newpath);
        copyFolder(f1,f2);
   }
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值