【问题标题】:Calling static directory-copying method in Java在 Java 中调用静态目录复制方法
【发布时间】:2012-10-06 17:37:32
【问题描述】:

我尝试使用这个问题的例子:How to copy a folder and all its subfolders and files into another folder

我将他设为静态,当我调用 copyDirectory() 时,程序运行时出现异常:

Exception in thread "AWT-EventQueue-0" java.lang.Error: Unresolved compilation problem: 
Unhandled exception type IOException

在使用此方法的每一行。

我加了

  throws IOException 

对于每个使用 copyDirectory() 的方法

错误的计数已被缩短,但它们仍保留在本地 java 类中。而且我无法编辑它们:这将是一个无限的编辑递归:))

Advance 我很抱歉英语不好。

UPD:(使用 ApacheCommonsIO)

import org.apache.commons.io.FileUtils;
// the rest import
public class MyClass{
  public myMethod(){
   String src = "/home/user/dir_src";
   String dst = "/home/user/dir_dst";
   FileUtils.copyDirectory(new File(src), new File(dst)); 
  }
}

【问题讨论】:

  • 它是一个编译时错误,所以首先尝试解决编译时错误然后去寻找异常
  • 是的,我使用 vim + eclim 插件。我没有“红线”和编译问题。
  • 您解决了编译时间错误吗?
  • 我通过在每个使用 copyDirectory() 的方法中添加“抛出 IOException”来解决它们。是错误的方式,但不知道如何纠正它们。
  • 你能发布你的代码吗?您必须处理代码中某处引发的异常

标签: java static directory ioexception


【解决方案1】:

这里有两件事

  1. 您应该像这样格式化您的方法 copyDirectory,这样它就不会抛出所有这些异常:


    public static boolean copyDirectory(File source, File destination) {
      try{
        // Copy Stuff
        return true;
      catch(IOException e){
        // Your way of ErrorLogging
        return false;
      }
    }

  1. 对于复制删除等所有 IO-Stuff,我建议您使用 ApachCommonIO:http://commons.apache.org/io/。

编辑:

现在请尝试这段代码,它至少应该可以编译并提示你出了什么问题:

import org.apache.commons.io.FileUtils;
// the rest import
public class MyClass{
  public myMethod(){
   String src = "/home/user/dir_src";
   String dst = "/home/user/dir_dst";
   try{
      FileUtils.copyDirectory(new File(src), new File(dst)); 
   catch(IOException e){
      e.printStackTrac();
   }
  }
}

【讨论】:

  • 按照你的建议,我安装了 ApacheCommonIO。我也有同样的问题:我的行 FileUtils.copyDirectory(new File(src), new File(dst));以“未处理的 IO 异常”突出显示。
  • 请提供您正在使用的代码。也许我们会在这里找到一个错误。对于 ApacheCommonsIO,这是一个库,它提供了处理 CommonIO 任务(如复制、删除等)的方法。请查看文档以获取有关如何操作的更多信息。
猜你喜欢
  • 2011-01-03
  • 1970-01-01
  • 2012-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多