簡體   English   中英

從 Java NIO2 中的臨時文件對 Files.copy 的 AccessDeniedException

[英]AccessDeniedException on Files.copy from a temporary file in Java NIO2

我已經習慣了 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);
}

所以你的問題不在於那個代碼。 它可能在您的代碼中的其他地方,或者由於您正在使用的文件/文件夾的權限。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM