【问题标题】:How can I copy a file and the directory structure where it exists?如何复制文件及其存在的目录结构?
【发布时间】:2013-11-26 01:05:50
【问题描述】:

我需要将文件从 A 复制到 B 但保留目录结构。

例如

C:\folder\second folder\myFile.txt
to 
C:\new folder\my second folder\myFile.txt

这样,如果我的新目的地不存在,它将被创建

我尝试了this 示例,但它复制了整个目录,而不仅仅是我指定的文件。

【问题讨论】:

标签: java


【解决方案1】:

利用File.mkdirs() 函数:创建以此抽象路径名命名的目录,包括任何必要但不存在的父目录。请注意,如果此操作失败,它可能已成功创建了一些必要的父目录。

在读取和写入文件之前,您可以检查文件路径是否存在,如果不存在则创建它。例如:

 String s = "c:\\A Dir\\B Dir\\myFile.txt";
 File f = new File(s);
 if(!f.getParentFile().exists())         
      f.getParentFile().mkdirs(); // create the parent directory "c:\\A Dir\\B Dir\\"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-02
    • 1970-01-01
    • 2012-08-17
    • 1970-01-01
    • 2017-05-19
    • 1970-01-01
    • 2021-05-24
    • 2014-09-06
    相关资源
    最近更新 更多