java文件拷贝

public static void main(String[] args) {
  // TODO Auto-generated method stub

  //测试拷贝文件
   String fromFile="F:/fieCopyTest/fromFile.xlsx";//fromFile.xlsx
         String toFile="F:/fieCopyTest/toFile.xlsx";
         try {
    copyFile(fromFile,toFile);
   } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
 }

 public static void copyFile(String fromFileName,String toFileName) throws Exception{
  
  File fromFile = new File(fromFileName);
  File toFile = new File(toFileName);
  
  //源文件不存在
  if(!fromFile.exists()){
   throw new Exception("FileCopy:"+"no such source file"+fromFileName);
  }
  //源文件不是合法文件
  if(!fromFile.isFile()){
   throw new Exception("FileCopy:"+"can't copy file"+fromFileName);
  }
  //源文件不能读取
  if(!fromFile.canRead()){
   throw new Exception("FileCopy:"+"can't Read file"+fromFileName);
  }
  
  //是否是目录文件
  if(toFile.isDirectory()){
   toFile = new File(toFile,fromFile.getName());
  }
  //目的文件是否存在
  if(toFile.exists()){
   //toFile不能读写
   if(!toFile.canWrite()){
    throw new Exception("fileCopy:"+"can not Write"+toFileName);
                  //System.out.print("OverWrite exiting file "+toFileName+"?(Y/N):");
                  //System.out.flush();
    
   }else{
    
    String parent = toFile.getParent();
    if(parent ==null){
     parent = System.getProperty("user.dir");
    }
    File dir = new File(parent);
    if(!dir.exists()){
     throw new Exception("fileCopy:"+"destination directory doesn't exist"+dir.getName());
    }
    if(!dir.isFile()){
     throw new Exception("fileCopy:"+"destination is not a file"+dir.getName());
    }
    if(!dir.canWrite()){
     throw new Exception("fileCopy:"+"destination can't to be write"+dir.getName());
    }
   }
  }
  FileInputStream from = null;
  FileOutputStream in =null;
  
  from = new FileInputStream(fromFile);
  in = new FileOutputStream(toFile);
  
  byte[] buffer = new byte[4096];
  int byteRead;
  //write 方式一,将文件读入字节流,可以读写 xlsx,xls,doc ,docx,txt等文件
  while((byteRead=from.read(buffer))!=-1){
   in.write(buffer,0,byteRead);//开始write操作
  }
  //write 方式二,直接读取文件,可以读写txt文件
  
  from.close();
  in.close();
 }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值