【问题标题】:Cannot Find Path Specified Creating File Despite Existing Parent Directory尽管存在父目录,但无法找到指定的创建文件的路径
【发布时间】:2018-01-16 22:17:10
【问题描述】:

我正在尝试将 zip 文件导出到目录并遇到 IOException,指出找不到文件路径。我知道这意味着父目录通常不存在,但是调试正在写入文件的行 file.getParentFile().exists() 返回 true,所以这不是我的问题。更复杂的是,这只发生在大约一半的写入文件中。通过 java 解压缩时总是失败的文件总是相同的文件,但通过 windows 解压缩它们总是成功的。

这是我正在使用的代码:

ZipInputStream zis =
                new ZipInputStream(new ByteArrayInputStream(zipFile));
ZipEntry ze = zis.getNextEntry();

while (ze != null) {
    String fileName = ze.getName();
    File newFile = new File(outputFolder + File.separator + fileName);
    if(!newFile.isDirectory()) {
        newFile.getParentFile().mkdirs();
        FileOutputStream fos = new FileOutputStream(newFile); //Exception occurs here
        //newFile.getParentFile().exists() returns true 
        //copying the path for newFile.getParentFile() into my file browser leads me to a valid, existing folder
        //I have tried newFile.createNewFile() and that errors with a similar exception

        int len;
        while ((len = zis.read(buffer)) > 0) {
            fos.write(buffer, 0, len);
        }

        fos.close();
        results.add(new Foo());
    }
    ze = zis.getNextEntry();
}

示例异常:

java.io.FileNotFoundException: \\foo\foo\foo\foo\foo\foo\foo.pdf (The system cannot find the path specified)

关于系统的一些注意事项:文件系统是远程网络驱动器,系统运行windows,并且该帐户对该驱动器具有完全写入权限。我还验证了命名文件 foo.pdf(复制并粘贴要写入的文件的名称)也不会导致任何问题。

【问题讨论】:

    标签: java file zip


    【解决方案1】:

    问题是 zip 文件的路径中可以有尾随空格。例如,“测试任何 .zip”可能是文件名,因此 java 将文件夹视为“/测试任何 /”并尝试创建该文件夹。 Windows 告诉 java 它成功了,但实际上它在“/Test What/”处创建了一个文件夹。在处理文件夹时,文件 IO 对此没有任何问题,但是在写入文件时,它会在明确查找路径时完全崩溃。它不会像处理文件夹时那样截断多余的空白,正如您所期望的那样。

    这是我用来解决它的代码:

    String path = (outputFolder + File.separator + fileName).replace(" ", "");
    
    File newFile = new File(path);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多