拷贝一个文件的算法比较简单,当然,可以对它进行优化,比如使用缓冲流,提高读写数据的效率等。但是在复制文件夹时,则需要利用Flie类在目标文件夹中创建相应的目录,并且使用递归方法.
拷贝文件夹内容
public static void copyfile(String inputpath, String outputpath) {
// TODO Auto-generated method stub
File inputfile = new File(inputpath);
File outputfile = new File(outputpath);
if(!inputfile.isDirectory())
{
File parentFile = outputfile.getParentFile();
parentFile.mkdirs();
CopyOneFile(inputpath, outputpath); //拷贝单一的文档
}
else
{
String[] nextfilename = inputfile.list();
outputfile.mkdirs();
for(String r : nextfilename)
{
copyfile(inputpath + File.separator + r, outputpath + File.separator + r); //递归拷贝
}
}
}
public static void CopyOneFile(String inputpath, String outputpath) {
BufferedInputStream inBuff = null;
BufferedOutputStream outBuff = null;
try {
inBuff = new BufferedInputStream(new FileInputStream(inputpath));
outBuff = new BufferedOutputStream(new FileOutputStream(outputpath));
// 缓冲数组
byte[] b = new byte[1024 * 5];
int len;
while ((len = inBuff.read(b)) != -1) {
outBuff.write(b, 0, len);
}
outBuff.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭流
if (inBuff != null) {
try {
inBuff.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (outBuff != null) {
try {
outBuff.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}