关于java的文件操作

zhangwei9730 2003-10-29 02:41:13
请假大家一个问题:
我如何用java实现把一个文件夹和它下面的程序拷贝到另一个文件夹下面阿?
...全文
21 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
loveyousomuch 2003-10-29
  • 打赏
  • 举报
回复
测试了一下代码,发现如有中文会造成乱码现象!!
okwuzhijun 2003-10-29
  • 打赏
  • 举报
回复
用递归的方法建目录拷贝目录下的文件
LoveRose 2003-10-29
  • 打赏
  • 举报
回复
最简单的实现就是用递归的方法了

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

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

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)
{
}

}
}
}
}
fft123 2003-10-29
  • 打赏
  • 举报
回复
windows平台下最简单的方法:用Runtime.exec调用windows提供的xcopy

62,614

社区成员

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

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