【技术心得】一个很方便的Java目录拷贝程序
在网上找到了一个比较好用的 Java 目录拷贝程序,自己用了一下很方便。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class DirCopyUtil
{
public static void copy(File src, File dest)
throws IOException
{
getCopyable(src).copy(dest);
}
// this is the factory pattern.
public static Copyable getCopyable(File src)
{
// if the source if file then return a file copier
if (src.isFile())
{
return new FileCopier(src);
}
/*
* else it has to be a directory copier, we could also enhance it to be
* other type of copier such as httpcopier etc...
*/
return new DirCopier(src);
}
interface Copyable
{
void copy(File dest)
throws IOException;
}
static class DirCopier
implements Copyable
{
File srcDir;
public DirCopier(File srcDir)
{
if (!srcDir.isDirectory())
{
throw new IllegalArgumentException(
"passed in paremter has to be directory" + srcDir);
}
this.srcDir = srcDir;
}
/**
* copy current directory content under 'destRoot' directory
*
* @param destRoot the destination root directory, all the file and sub
* directory will be copied under this destRoot directory, if
* destRoot doesn't exist, this will create the directory.
* @throws IOException
*/
public void copy(File destRoot)
throws IOException
{
// 1) if destRoot is not exist it will create it
if (!destRoot.exists())
{
if (!destRoot.mkdirs())
{
throw new IOException("unable to create dir:" + destRoot);
}
}
if (!destRoot.isDirectory())
{
throw new IllegalArgumentException(
"passed in paremter has to be directory" + destRoot);
}
File[] dirContents = srcDir.listFiles();
// we know dirContents can not be null since only file will return
// null, so no need to check null
for (int i = 0; i < _srcfile =" dirContents[i];" _srcpath =" _srcFile.getCanonicalPath();" _srcpath =" _srcPath.substring(0," dest =" new" src =" src;" in =" new" out =" new" buffer =" new" len =" 0;" len =" in.read(buffer,"> 0)
{
out.write(buffer, 0, len);
}
in.close();
out.close();
}
}
}

1 条评论:
c ++语言示例
找到一个游戏这个词
发表评论