100分解决复制整个目录

yryd 2003-11-04 05:27:18
请教在java里怎么复制一个目录
...全文
28 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
loveyousomuch 2003-11-04
  • 打赏
  • 举报
回复
测试了一下楼上的代码,呵呵,不错!!
代码少,清晰,学习……
pqds 2003-11-04
  • 打赏
  • 举报
回复
public void copyallfile(String path1,String path2) throws IOException
{
File f=new File(path1);
if(f.isDirectory() ){

File temp = new File(path2);
if(!temp.isDirectory()) temp.mkdir();

File files[]=f.listFiles() ;
for (int i = 0; i < files.length; i++) {
if(!files[i].isDirectory())
{
FileInputStream fi = new FileInputStream(files[i].toString());
FileOutputStream fo = new FileOutputStream(path2+"\\"+files[i].getName());
byte date[] = new byte[fi.available()];
fi.read(date);
fo.write(date);
fi.close();
fo.close();
}else
{
copyallfile(files[i].toString(),
path2+"\\"+files[i].getName());
}
}

}

}
LoveRose 2003-11-04
  • 打赏
  • 举报
回复
一个demo程序,应该还是有帮助的

import java.io.*;
import java.util.*;

public class TestCopy
{
public static void main(String[] args)
{
TestCopy test = new TestCopy();
test.copyTo(new StringBuffer("f:/books"), new StringBuffer("f:/booksCOPY"));
}

public void copyTo (StringBuffer s_path, StringBuffer t_path)
{
File s_file = new File(s_path.toString());
File t_file = new File(t_path.toString());
if (!t_file.exists())
t_file.mkdir();
File[] files = s_file.listFiles();
for (int i = 0; i < files.length; i++)
{
System.out.println(files[i].getName());
if (files[i].isDirectory())
{
StringBuffer s_subPath = new StringBuffer(s_path.toString());
StringBuffer t_subPath = new StringBuffer(t_path.toString());
t_subPath.append("/");
s_subPath.append("/");
t_subPath.append(files[i].getName());
s_subPath.append(files[i].getName());
File subDir = new File(t_subPath.toString());
if (subDir.mkdir())
copyTo(s_subPath, t_subPath);
}
else if (files[i].isFile())
{
File t_subFile = new File(t_path.toString() + "/" + files[i].getName());
File s_subFile = new File(s_path.toString() + "/" + files[i].getName());
try
{
FileInputStream fin = new FileInputStream(files[i]);
FileOutputStream fout = new FileOutputStream(t_subFile);
int length;
while ((length = fin.read()) != -1)
{
byte[] buffer = new byte[1024];
fin.read(buffer, 0, length);
fout.write(buffer, 0, length);
}
}
catch (IOException ioe)
{
}
catch (Exception e)
{
}

}
}
}
}

62,614

社区成员

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

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