简体   繁体   English

在Java中调用静态目录复制方法

[英]Calling static directory-copying method in Java

I try to use example from this question : How to copy a folder and all its subfolders and files into another folder 我尝试使用以下问题的示例: 如何将一个文件夹及其所有子文件夹和文件复制到另一个文件夹中

I made him static, and when I call copyDirectory(), I have an exception during program runs : 我将他设为静态,当我调用copyDirectory()时,在程序运行期间出现异常:

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

At every line that uses this method. 在使用此方法的每一行。

I added 我加了

  throws IOException 

for every method that uses copyDirectory() 对于使用copyDirectory()的每个方法

Error's count had been shorted, but they remained at native java classes. 错误的计数已被缩短,但它们仍保留在本机Java类中。 And I can't edit them : it would be an infinite editing recursion :)) 而且我无法编辑它们:这将是无限的编辑递归:))

Advance I'm sorry for bad english. 前进对不起英语不好。

UPD: (Using ApacheCommonsIO) 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)); 
  }
}

2 Things here 2件事在这里

  1. You should format your method copyDirectory somehow like this, so it won't throw you all these exceptions: 您应该以某种方式设置方法copyDirectory的格式,因此它不会引发所有这些异常:


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

  1. For all the IO-Stuff like copying deleting and so on I would recommend you using ApachCommonIO: http://commons.apache.org/io/ . 对于所有IO-Stuff,例如复制删除等等,我建议您使用ApachCommonIO: http ://commons.apache.org/io/。

Edit: 编辑:

Please try this code now, this should at least compile and give you a hint what is wrong: 请立即尝试这段代码,至少应该编译一下,然后提示您什么地方不对:

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();
   }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM