4

我已经习惯了 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 用户创建的目录。

似乎问题在于从临时文件中读取,因为直接写入目标是可行的。我接下来应该看哪里?

4

1 回答 1

2

不是答案,但评论太长了。我运行下面的代码(从 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);
}

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

于 2014-04-01T08:38:48.517 回答