file.getParentFile()mkdirs();在osx中​​创建重复的文件夹

时间:2013-01-19 21:02:20

标签: java macos file exception directory

我正在开发一个专门用于windows和osx的程序,我有这个函数来复制一个在windows中完美运行的文件,但是当我在osx中​​尝试它时,我得到一个IOException:“没有这样的文件或目录” ,我研究了一下,发现可能目的地目录不存在(虽然它确实存在)所以我添加了这些行:

if(!f2.getParentFile().exists())
{
    f2.getParentFile().mkdirs();
}
if(!f2.exists())
{
   f2.createNewFile();
}

这似乎解决了这个问题,但是当我找到复制的文件(位于文档)时,我一开始找不到它,但后来我看到该程序实际上创建了一个我想要的重复文件夹将文件保存到,所以我最终得到了两个文件夹,其中包含完全相同的“文档”名称,这是代码的其余部分:

    public static Boolean copyfile(String srFile, String dtFile )
{
    {
          try
          {
          File f1 = new File(srFile);
          File f2 = new File(dtFile);
          if(!f2.getParentFile().exists())
          {
              f2.getParentFile().mkdirs();
          }
          if(!f2.exists())
          {
              f2.createNewFile();
          }
          InputStream in = new FileInputStream(f1);
          OutputStream out = new FileOutputStream(f2);

          byte[] buf = new byte[1024];
          int len;
          while ((len = in.read(buf)) > 0){
          out.write(buf, 0, len);
          }
          in.close();
          out.close();
          System.out.println("File copied.");
          }
          catch(FileNotFoundException ex){
          System.out.println(ex.getMessage() + " in the specified directory.");
          JOptionPane.showMessageDialog(new JFrame(), ex.getMessage());
          return true;
          }
          catch(IOException e){
          System.out.println(e.getMessage());  
          JOptionPane.showMessageDialog(new JFrame(), e.getMessage());
          return true;
          }
          }
    return false;
}

这显然不是理想的结果,我该怎么办才能识别我要保存文件的文件夹?

更新:我使用了ls -B命令,它显示了两个不同语言的文件夹:“Documents”和“Documentos”,即使它们在finder中都显示为“Documentos”

2 个答案:

答案 0 :(得分:2)

  

所以我最终得到了两个文件夹,其中包含完全相同的“文档”名称,

那不可能发生。这两个目录(可能非常巧妙地)有不同的名称。例如,名称中可以有一个尾随空格等。

一旦你弄清楚名称的不同之处,就应该很清楚如何解决这个问题。

您可以使用以下命令对此进行故障排除: ls -B应将任何不可打印的字符显示为\xxx。至于尾随空格等,请尝试ls -1 | od -c并仔细检查输出。

答案 1 :(得分:0)

如果您使用的是Java 7,请尝试使用java.nio.file包。错误(如果有的话)应该提供更多信息:

Path source = Paths.get(srFile);
Path dest = Paths.get(dtFile);
Files.createDirectories(dest.getParent());
Files.copy(source, dest);

我建议你不要调用Throwable的getMessage()方法。除了在异常类旁边显示之外,它通常提供没有意义的信息。因此,请使用println(ex.getMessage())而不是println(ex)。当然,比其中任何一个都更有用ex.printStackTrace()