代码之家  ›  专栏  ›  技术社区  ›  Silver Quettier

从Java NIO2中的临时文件对Files.copy执行AccessDeniedException

  •  5
  • Silver Quettier  · 技术社区  · 11 年前

    我已经习惯了Java 7和新的 Files

    我正在编写一个小应用程序,在某些时候,它必须替换文件的内容。 我使用了一个临时文件,以避免在出现错误时删除目标文件。然而,我总是得到一个 AccessDeniedException 当执行实际复制时。

    这是我的代码:

    // Temporary file generation.
    Path target = getCurrentConfigFile(); // Returns a path, works ok.
    Path tempFile = Files.createTempFile("tempfile", null);
    Files.write(tempFile, conf.getBytes(Charset.defaultCharset()), StandardOpenOption.WRITE);
    
    // Actual copy.
    Files.copy(tempFile, target, StandardCopyOption.REPLACE_EXISTING);
    
    // Cleanup.
    Files.delete(tempFile);
    

    getCurrentConfigFile() 处理目标文件路径创建:

    (... generates various strings from configuration parameters)
    return FileSystems.getDefault().getPath(all, these, various, strings);
    

    当我执行代码时,它通过 .bat 脚本,并且我通过标准命令提示符或提升获得错误。 目标文件位于 C:\temp\tests ,我用同一个Windows用户创建的目录。

    问题似乎在于读取临时文件,而不是直接写入目标文件。 我下一步应该去哪里?

    1 回复  |  直到 11 年前
        1
  •  2
  •   assylias    11 年前

    没有回答,但评论太长了。我运行了下面的代码(在Windows 7上从命令行),它可以按预期工作:

    public static void main(String[] args) throws IOException {
        Path target = Paths.get("C:/temp/test.txt"); // Returns a path, works ok.
        Path tempFile = Files.createTempFile("tempfile", null);
        Files.write(tempFile, "abc".getBytes(UTF_8), StandardOpenOption.WRITE);
    
        // Actual copy.
        Files.copy(tempFile, target, StandardCopyOption.REPLACE_EXISTING);
    
        // Cleanup.
        Files.delete(tempFile);
    }
    

    所以你的问题不在于代码。它可能在代码中的其他位置,或者由于您正在使用的文件/文件夹的权限。