【问题标题】:Copying saved files from a List<File> into a directory recursively in java在java中递归地将保存的文件从 List<File> 复制到目录中
【发布时间】:2016-01-03 17:39:27
【问题描述】:

我已经搜索过这个答案,我试图解决这个问题,但我不能。我得到了类型的异常

No fue posible copiar los archivos. Motivo: C:\Test1 (Acceso denegado)java.io.FileNotFoundException: C:\Test1 (Acceso denegado)
java.io.FileNotFoundException: C:\Test1 (Acceso denegado)

翻译后的内容类似于“无法复制文件。动机:(拒绝访问)”。

我想要做的是将一个列表递归地复制到一个目录中。

我可以简单地递归复制文件(我已经这样做了),但要求是将所有文件复制到一个列表中,然后对列表中的记录做任何我想做的事情(复制、删除等)。

我的列表包含以下记录:

C:\Test\Carpeta_A
C:\Test\Carpeta_A\Entrenamiento_1.txt
C:\Test\Carpeta_A\Requerimientos.txt
C:\Test\Carpeta_B
C:\Test\Carpeta_B\queries.txt
C:\Test\Things.txt

这是我的代码:

这是主要方法..它调用一个方法来列出和保存文件和目录,然后调用将文件复制到另一个目录的方法,保留我的主要结构:

public static void main(String[] args) throws IOException
{
        String fuente = "C:/Test";
        String ruta   = "C:/Test1";
        teeeeeest listing = new teeeeeest();
        List<File> files = listing.getFileListing(fuente);

        listing.copyDirectories(files, ruta);         
}

 public List<File> getFileListing( String fuente ) throws FileNotFoundException
 {              
            List<File> result = getFileListingNoSort(fuente);
            Collections.sort(result);
            return result;
  }

 private List<File> getFileListingNoSort( String fuente ) throws FileNotFoundException 
 {
            File source = new File(fuente);
            List<File> result = new ArrayList<>();
            File[] filesAndDirs = source.listFiles();
            List<File> filesDirs = Arrays.asList(filesAndDirs);
            for(File file : filesDirs) {
              result.add(file); //always add, even if directory
              String s = file.getPath().trim();
              if (! file.isFile()) {
                //must be a directory
                //recursive call!
                List<File> deeperList = getFileListingNoSort(s);
                result.addAll(deeperList);
              }
            }
            return result;
  }

public static void copyDirectories(List<File> files, String destiny) 
            throws IOException 
    {
        InputStream in   = null;
        OutputStream out = null;
        File targetPath = new File(destiny);
        System.out.println(targetPath.getPath());


        for(int i = 0; i < files.size(); i++)
        {
            File temp = new File(files.get(i).toString());
            //System.out.println(temp.getPath());               

            try
            {
                if(temp.isDirectory())
                {
                    if(!targetPath.exists())
                    {
                        targetPath.mkdir();
                    }                                               


                    File[] filesAndDirs = temp.listFiles();
                    List<File> filesDirs = Arrays.asList(filesAndDirs);
                    for(File file : filesDirs) 
                    {  

                      if (! file.isFile())
                      {
                        //must be a directory
                        //recursive call!
                          copyDirectories(filesDirs,destiny);

                      }
                    }

                }
                else
                {
                    in = new FileInputStream(files.get(i).toString());
                    out = new FileOutputStream(targetPath);
                    System.out.println(temp.getPath());                    

                    byte[] buf = new byte[1024];
                    int len;
                    while ((len = in.read(buf)) > 0) 
                    {
                        out.write(buf, 0, len);
                    }
                }                   
            }
            catch(Exception e)
            {
                System.err.println("No fue posible copiar los archivos. Motivo: " + e.getMessage() + e);
                e.printStackTrace();

            }           
        }
    }

【问题讨论】:

  • 第一个例外是FileNotFoundException,它拒绝访问,因为它首先找不到文件/目录。当您尝试阅读或尝试写入时是否会引发异常? C:\Test1 是您的目标文件夹吗?
  • C:\Test1 存在吗?
  • 是的,C:\Test1 存在,是的,它是目标文件夹,在调试时我在这一行得到了异常:out = new FileOutputStream(targetPath);
  • 如果您打开命令提示符,导航到 c:\test1 并输入 echo XXX > test.out 会发生什么?这将测试您是否对该目录具有写入权限。
  • Dit it.. 答案是肯定的。我有写权限。

标签: java list recursion


【解决方案1】:

将工作代码粘贴在这里对我来说是非常糟糕的,它不会帮助您思考问题所在。我会尽量给你足够的东西而不给你一切:如果对你有帮助,请将我的回答标记为已接受。

1:您不应该对文件列表进行排序。读取文件的顺序很重要,这样您就不会在列表中的目录之前获取文件。也就是说,是否对它们进行排序并不重要,因为较短的名称(即目录)无论如何都会首先出现。不过,不要做你不应该做的工作。移除 getFileListing 方法,只使用 getFileListingNoSort。

List<File> files = listing.getFileListingNoSort(fuente);

2:您需要将源目录和目标目录都传递给copyDirectories,以便您可以从源文件名中生成目标文件名。

listing.copyDirectories(files, fuente, ruta);

3:您需要从源文件名中创建一个目标文件。可能有更好的方法,但使用简单的字符串解析就可以了:

File temp = files.get(i);
String destFileName = destiny + temp.toString().substring(source.length());
File destFile = new File(destFileName);

4:您必须根据新的 destFile 创建新目录。您使用的是targetPath,它只是基本目录,而不是需要创建的新目录。

if(!destFile.exists())
{
    destFile.mkdir();
}                                               

5: 制作好目标目录后,就没有什么可做的了。删除之后的所有代码,直到 'else'

6:您的 outfile 应该是您创建的新 destFile。

out = new FileOutputStream(destFile);

7:关闭输入输出流,否则文件拷贝不完整。

in.close();
out.close();

这应该会让你继续前进。如果可以,请使用 IDE,这样您就可以使用调试器单步执行程序并查看发生了什么。

【讨论】:

  • 谢谢尼古拉斯。我会照你说的做,然后我会告诉你结果
  • 有效!!我已经进行了更改并且它有效。非常感谢。
【解决方案2】:

在您的 copyDirectories 方法调用中,命运始终是相同的值,即使在递归调用中也是如此。您正在将所有文件复制到同一个目标文件。

【讨论】:

    猜你喜欢
    • 2012-07-31
    • 1970-01-01
    • 2014-11-07
    • 2015-03-01
    • 1970-01-01
    • 2010-12-31
    • 2021-06-06
    • 1970-01-01
    • 2015-05-18
    相关资源
    最近更新 更多