我正在习惯 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 用户创建的目录。
似乎问题出在从临时文件中读取,因为直接写入目标是可行的。 接下来我应该看哪里?
最佳答案
不是答案,但评论时间太长。我运行下面的代码(从 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);
}
所以您的问题不在于该代码。它可能在您的代码中的其他地方,或者由于您正在使用的文件/文件夹的权限。
关于java - Files.copy 上的 AccessDeniedException 来自 Java NIO2 中的临时文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22779916/