文件或文件夹复制

chen_qing_zhen 2012-12-12 03:30:38
package copyfileordirectory;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
*
* @author Administrator
*/
public class CopyFileOrDirectory {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String from = null;
String to = null;

try {
System.out.println("请输入已存在的源文件夹或源文件的路径:");
from = reader.readLine();
System.out.println("请输入目标文件夹或目标文件的路径:");
to = reader.readLine();
File sourceDir = new File(from);
File objectDir = new File(to);
File[] directory = sourceDir.listFiles();
for (File dir : directory) {
if (dir.isFile()) {
copyFile(dir.getAbsolutePath(), to + "/" + dir.getName());
}
if (dir.isDirectory()) {
copyDirectory(from+"/"+dir.getName(),to+"/"+dir.getName());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}

public static void copyFile(String from, String to) throws IOException {
BufferedInputStream in = new BufferedInputStream(new FileInputStream(from));
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(to));
int length = 0;
byte[] b = new byte[1024];
while ((length = in.read()) != -1) {
out.write(b, 0, length);
}
in.close();
out.close();
}

public static void copyDirectory(String from, String to) throws IOException {
File sourceDir = new File(from);
File objectDir = new File(to);
File[] directory = sourceDir.listFiles();
for (File dir : directory) {
if (dir.isFile()) {
copyFile( dir.getAbsolutePath(), new File(to).getAbsolutePath() + "/" + dir.getName());
}
if (dir.isDirectory()) {
String fromdir=from+"/"+dir.getName();
String todir=to+"/"+dir.getName();
copyDirectory(fromdir,todir);
}
}
}
}

以上是实现文件或文件夹的源代码,但运行后只能复制文件而不能复制文件夹,跪求各位大神的帮助!!!
...全文
486 14 打赏 收藏 转发到动态 举报
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
chen_qing_zhen 2013-01-05
  • 打赏
  • 举报
回复
引用 12 楼 abstruct 的回复:
写了一个,测试可以使用。看看吧 Java code?123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657package com.study.test; import java.io.File;import java……
十二楼的是可以实现文件夹复制,不过是把DOC整个文件夹复制到11文件夹中,还是挺感谢的。。。
faping_cao 2012-12-17
  • 打赏
  • 举报
回复
public static void copyFileByName(String sourcePathname, String newPathname) {
		File sourceFile = new File(sourcePathname);
		File newFile = new File(newPathname + File.separator
				+ sourceFile.getName());
		copyFileByFile(sourceFile, newFile, false);
	}

	/**
	 * 
	 * @param sourceFile
	 * @param newFile
	 * @param flag
	 *            false复制,true剪切
	 */
	public static void copyFileByFile(File sourceFile, File newFile,
			boolean flag) {
		if (sourceFile.isFile()) {
			copyFileByStream(sourceFile, newFile);
		} else {
			newFile.mkdir();
			for (File file : sourceFile.listFiles()) {
				copyFileByFile(file, new File(newFile.getPath()
						+ File.separator + file.getName()), flag);
			}
		}

		if (flag) {
			sourceFile.delete();
		}
	}

/**
	 * 复制文件
	 * 
	 * @param sourceFile
	 * @param newFile
	 */
	public static void copyFileByStream(File sourceFile, File newFile) {
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			fis = new FileInputStream(sourceFile);
			fos = new FileOutputStream(newFile);
			writeRead(fos, fis);
		} catch (Exception e) {
			throw new UtilException(e.getMessage());
		} finally {
			closeInputStream(fis);
			closeOutputStream(fos);
		}

	}

安特矮油 2012-12-17
  • 打赏
  • 举报
回复
写了一个,测试可以使用。看看吧

package com.study.test;

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;

public class Test {

	public static void main(String[] args) throws Exception {
		File file = new File("D:\\DOC");
		copy(file, "D:\\11");
	}
	
	public static void copy(File file, String dir){
		File direstory = new File(dir);
		direstory.mkdir();
		InputStream in = null;
		OutputStream out = null;
		if(file.isDirectory()){
			File[] files = file.listFiles();
			for(File f : files){
				copy(f, dir + File.separator + file.getName());
			}
		}else{
			try {
				in = new FileInputStream(file);
				out = new FileOutputStream(dir + File.separator + file.getName());
				int i;
				byte[] buf = new byte[1024];
				while((i = in.read(buf)) != -1){
					out.write(buf, 0, i);
				}
				out.flush();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				try {
					if(in != null){
						in.close();
					}
					if(out != null){
						out.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
		}
	}
}
fish8245 2012-12-15
  • 打赏
  • 举报
回复
你的问题是第58行:少了字节数组! 改为 while ((length = in.read(b)) != -1) { 再试一试
chen_qing_zhen 2012-12-15
  • 打赏
  • 举报
回复
引用 7 楼 AA5279AA 的回复:
引用 6 楼 cl1_1_1_1 的回复:没分,发帖,顺便搭下车, 请问下有没有大神,用过测试垃圾邮件的数据集? It is better for you to search the benchmark dataset for DDoS/DoS, spam solution test purpose. 好崩溃,不要这样搭车啊。。重新建个号就是了。。。 ……
被复制的文件不为空,而且都是可以打开的,复制后的文件有大小,但是打开却为空,要么就是打不开。
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package copyfileordirectory;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 *
 * @author Administrator
 */
public class CopyFileOrDirectory {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String from = null;
        String to = null;

        try {
            System.out.println("请输入已存在的源文件夹或源文件的路径:");
            from = reader.readLine();
            System.out.println("请输入目标文件夹或目标文件的路径:");
            to = reader.readLine();
            File sourceDir = new File(from);
            File objectDir = new File(to);
            objectDir.mkdirs();
            File[] directory = sourceDir.listFiles();
            for (File dir : directory) {
                if (dir.isFile()) {
                    copyFile(dir.getAbsolutePath(), to + "/" + dir.getName());
                }
                if (dir.isDirectory()) {
                    copyDirectory(from+"/"+dir.getName(),to+"/"+dir.getName());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void copyFile(String from, String to) throws IOException {
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(from));
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(to));
        int length = 0;
        byte[] b = new byte[1024];
        while ((length = in.read()) != -1) {
            out.write(b, 0, length);
        }
        in.close();
        out.close();
    }

    public static void copyDirectory(String from, String to) throws IOException {
        File sourceDir = new File(from);
        File objectDir = new File(to);
        objectDir.mkdirs();
                    File[] directory = sourceDir.listFiles();
            for (File dir : directory) {
                if (dir.isFile()) {
                    copyFile( dir.getAbsolutePath(), new File(to).getAbsolutePath() + "/" + dir.getName());
                }
                if (dir.isDirectory()) {
                    String fromdir=from+"/"+dir.getName();
                    String todir=to+"/"+dir.getName();
                    copyDirectory(fromdir,todir);
                }
            }
    }
}
以上是程序的源代码。跪求大神的出现。。。
aotian16 2012-12-13
  • 打赏
  • 举报
回复
其实你可以用apache的IO包 直接用也可以, 参考代码也行
失落夏天 2012-12-13
  • 打赏
  • 举报
回复
引用 3 楼 I_can_move_you 的回复:
复制是可以了,但是现在突然发现了一个新的问题,就是复制后的文件打不开了,我用的是面向字节的,如果用面向字符的是否会好一点呢?
你看看被复制生成的那个文件的大小,是否为空文件。
失落夏天 2012-12-13
  • 打赏
  • 举报
回复
引用 6 楼 cl1_1_1_1 的回复:
没分,发帖,顺便搭下车, 请问下有没有大神,用过测试垃圾邮件的数据集? It is better for you to search the benchmark dataset for DDoS/DoS, spam solution test purpose.
好崩溃,不要这样搭车啊。。重新建个号就是了。。。
overtake1984 2012-12-12
  • 打赏
  • 举报
回复
public static boolean copyDir(String fromDir,String toDir) {
           File in=new File(fromDir);
           File out=new File(toDir);
           if (!in.exists()) {
               return false;
           }
          
           if (!out.exists()) {
                out.mkdirs();
           } else {
               
           }
           
           File[] file=in.listFiles();
           FileInputStream fis=null;
           FileOutputStream fos=null;
           for (int i=0;i<file.length;i++) {
	             if (file[i].isFile()) {
					 try {
				         fis=new FileInputStream(file[i]);
				         File f = new File(toDir+"/"+file[i].getName());
				         fos=new FileOutputStream(f);
					 } catch (FileNotFoundException e) {
						 e.printStackTrace();
					 } 
	
	                 int c;
	                 byte[] b=new byte[1024*5];
	                 try {
	                     while((c=fis.read(b))!=-1){
	                         fos.write(b, 0, c);
	                     }
	                     fis.close();
	                     fos.flush();
	                     fos.close();
	                 } catch (IOException e) {
	                     e.printStackTrace();
	                 }
	             }
	             else {
	            	 copyDir(fromDir+"/"+file[i].getName(),toDir+"/"+file[i].getName());
	             }
           }
           return true;
       }
she383 2012-12-12
  • 打赏
  • 举报
回复
引用 3 楼 I_can_move_you 的回复:
复制是可以了,但是现在突然发现了一个新的问题,就是复制后的文件打不开了,我用的是面向字节的,如果用面向字符的是否会好一点呢?
这种场景都是用字节流~!
chen_qing_zhen 2012-12-12
  • 打赏
  • 举报
回复
复制是可以了,但是现在突然发现了一个新的问题,就是复制后的文件打不开了,我用的是面向字节的,如果用面向字符的是否会好一点呢?
chen_qing_zhen 2012-12-12
  • 打赏
  • 举报
回复
好的,我试试!
yuimyniit 2012-12-12
  • 打赏
  • 举报
回复
文件夹是不能通过io复制的,你需要自己mkdir

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧