A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© §傻、才乖 中级黑马   /  2014-1-19 15:44  /  2197 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 §傻、才乖 于 2014-1-19 20:41 编辑

自己写了个拷贝多级文件的代码如下:
  1. package javabase;

  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FileOutputStream;
  5. import java.io.InputStream;

  6. public class CopyLayersFile {
  7. public static void main(String[] args) throws Exception {
  8. copyDir("F:/learntest", "D:");
  9. }

  10. public static void copyDir(String src, String dest) throws Exception {
  11. File srcFile = new File(src);
  12. if (!srcFile.exists())
  13. return;
  14. if (srcFile.isHidden())
  15. return;
  16. String srcPath = srcFile.getAbsolutePath();
  17. System.out.println(srcPath);
  18. String destPath = dest+"\\"+srcFile.getName();
  19. System.out.println(destPath);
  20. File destFile = new File(destPath);/**/
  21. File[] files = srcFile.listFiles();
  22. destFile.mkdir();
  23. for (File file : files) {

  24. if (file.isDirectory()) {
  25. copyDir(file.getAbsolutePath(), destFile.getAbsolutePath());
  26. } else {
  27. copy(file.getAbsolutePath(), destFile.getAbsolutePath());
  28. }
  29. }
  30. }

  31. private static void copy(String from, String to) throws Exception {
  32. InputStream in = new FileInputStream(from);
  33. FileOutputStream out = new FileOutputStream(to);
  34. byte[] bytes = new byte[1024];
  35. int len = 0;
  36. while ((len = in.read(bytes)) != -1) {
  37. out.write(bytes, 0, len);
  38. }
  39. in.close();
  40. out.close();
  41. }
  42. }
复制代码

提示错误:
F:\learntest
D:\learntest
F:\learntest\.metadata
D:\learntest\.metadata
Exception in thread "main" java.io.FileNotFoundException: D:\learntest\.metadata (拒绝访问。)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:194)
at java.io.FileOutputStream.<init>(FileOutputStream.java:84)
at javabase.CopyLayersFile.copy(CopyLayersFile.java:38)
at javabase.CopyLayersFile.copyDir(CopyLayersFile.java:31)
at javabase.CopyLayersFile.copyDir(CopyLayersFile.java:29)
at javabase.CopyLayersFile.main(CopyLayersFile.java:10)

exception.png (9.2 KB, 下载次数: 42)

exception.png

2 个回复

倒序浏览
大神都去哪了,来个大神给解释下
回复 使用道具 举报
做了小小的修改 可以了  你看看

System.out.println(srcPath);
File destFile = new File(dest);
destFile.mkdirs();
File[] files = srcFile.listFiles();
for (File file : files) {
String destPath = dest+"\\"+file.getName();
if (file.isDirectory()) {
copyDir(file.toString(), destPath);
}
else {
copy(file.toString(), destPath);
}
}
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马