您的位置:首页 > 编程语言 > Java开发

Java 实现文件拷贝

2018-02-06 22:35 169 查看
package cn.weida.io.File;
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;
/**

 *

 * 文件拷贝

 * srcpath 源文件目录

 * aimpath 目标文件

 * @author 24569

 *

 */
public class FileUtils {

 public static void copyFile(String srcpath, String aimpath) throws FileNotFoundException, IOException {

  File src = new File("srcpath");

  File aim = new File("aimpath");

  copyFile(src, aim);

 }
 public static void copyFile(File src, File aim) throws FileNotFoundException, IOException {

  if (!src.isFile()) {

   throw new IOException("只能拷贝文件");

  }

  InputStream in = new FileInputStream(src);

  OutputStream out = new FileOutputStream(aim);

 /* byte[] car = new byte[10240];

  int len = 0;

  while (-1 != (len = in.read(car))) {

   out.write(car);

  }

  */

  /*String line = null;

  while (null!=(line=in.readLine())){

   out.write(line);

  }

  */

  in.close();

  out.close();

 }
 // 拷贝文件
 public static void copyDictory(String srcpath, String aimpath) throws FileNotFoundException, IOException {

  File src = new File(srcpath);

  File aim = new File(aimpath);

  copyDictory(src, aim);
 }
 public static void copyDictory(File src, File aim) throws FileNotFoundException, IOException {

  if (aim.isDirectory() && src.isFile()) {

   FileUtils.copyDictory(src, new File(aim.getPath(), src.getName()));

   return;

  } else if (src.isFile()) {

   FileUtils.copyFile(src, aim);

   return;

  } else {

   aim = new File(aim, src.getName());

   if (aim.isDirectory()) {

    throw new IOException(aim.getAbsolutePath() + "不能建立同名的文件夹");

   }

   aim.mkdirs();

   File[] Lin = src.listFiles();

   for (File temp : Lin) {

    copyDictory(temp, new File(aim, temp.getName()));

   }

  }

  return;
 }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: