本帖最后由 cuilitang 于 2013-10-24 00:31 编辑
- package cn.itcast;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.util.Scanner;
- public class CopyDemo {
- public static void main(String[] args){
- //String src = "G:\\temp"; 将这两个字符串改由Scanner接收
- //String dest = "F:";
- Scanner sc = new Scanner(System.in);
-
- System.out.println("请输入需要被拷贝的文件夹的路径(路径中斜杠请使用双斜杠):");
- String src = sc.next();
- System.out.println("请输入拷贝目标位置:");
- String dest = sc.next();
- File srcfile = new File(src);
- File destfile = new File(dest);
- try{
- copy(srcfile,destfile);
- }catch(Exception e){
- throw new RuntimeException("拷贝文件失败,请检查源文件或者目标位置是否存在");
- }
- System.out.println("拷贝完毕,请查看。");
-
-
- }
-
- public static void copy(File srcfile,File destfile) throws Exception{
- //在目标位置创建同名文件夹
- File newDir = new File(destfile,srcfile.getName());
- newDir.mkdir();
- //遍历源文件夹
- File[] subFiles = srcfile.listFiles();
- for (File subfile : subFiles) {
- // 输出文件名,测试文件是否遍历成功
- String name = subfile.getName();
- System.out.println(name);
- //如果是文件,直接拷贝
- if(subfile.isFile()){
- FileInputStream fileInputStream = new FileInputStream(subfile);
- FileOutputStream fileOutputStream = new FileOutputStream(new File(newDir,subfile.getName()));
-
- int i = 0;
- byte [] arr = new byte[1024];
- while((i = fileInputStream.read(arr)) != -1){
- fileOutputStream.write(arr,0,i);
- fileOutputStream.flush();
- }
- fileInputStream.close();
- fileOutputStream.close();
- //如果不是文件夹,递归调用拷贝方法
- }else{
- copy(subfile,newDir);
- }
-
- }
-
- }
- }
复制代码
|
|