首页 > 技术文章 > java复制File文件操作

qgc88 2013-09-25 13:00 原文

==========================复制File操作=========================

 /**
  *
  * @param newPath要赋值的路径
  * @param newName新文件名称
  * @param oldPath 旧文件路径
  * @return error 或者newPath + "/"+newName
  */
 @SuppressWarnings("unused")
 public static String complyFile(String newPath,String newName,String oldPath){
  //String newPath = "WebRoot/WEB-INF/1";// 复制的新路径
  //String oldPath = "WebRoot/WEB-INF/ebusiness.db";// 旧文件
  try {
   
  File file = new File(oldPath);

  int bytesum = 0;
  int byteread = 0;
  if (file.exists()) { // 文件存在时
   // 创建文件夹
   File file2 = new File(newPath);
   if (!file2.exists()) {
    // 创建文件夹
    file2.mkdirs();
   }
   
   File fileName = new File(newPath + "/"+newName);//新文件名和路径
   if(!fileName.exists()){//如果文件不存在
    fileName.createNewFile();
    FileUtils.copyFile(file,fileName);//fileName文件名,file要复制的文件
   }
   
   //以下的方法是使用流的方式复制,这种方式有时会损坏文件
   /*InputStream inStream = new FileInputStream(file); // 读入原文件
   FileOutputStream fs = new FileOutputStream(newPath + "/"+newName); // 复制文件
   byte[] buffer = new byte[1444];
   System.out.println(inStream.read(buffer));
   while ((byteread = inStream.read(buffer)) != -1) {
    bytesum += byteread; // 字节数 文件大小
    System.out.println(bytesum);
    fs.write(buffer, 0, byteread);
   }
   inStream.close();*/


  } else {
   System.out.println("文件不存在");
   return "error";
  }
  } catch (Exception e) {
   e.printStackTrace();
   return "error";
  }
  return newPath + "/"+newName;

 }

推荐阅读