Question

I am getting used to Java 7 and the new Files class.

I am writing a small application which, at some point, must replace the contents of a file. I used a temporary file to avoid erasing the target file if somethign goes wrong. However, I'm always getting an AccessDeniedException when performing the actual copy.

Here is my code:

// 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() handles the target file Path creation:

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

When I execute the code, it's through a .bat script, and I get the error both with a standard Command Prompt or elevation. The target file is in C:\temp\tests, a directory I created with the same Windows user.

It seems the problem lies in reading from the temporary file, as writing directly to the target works. Where should I look next?

Was it helpful?

Solution

Not an answer but too long for a comment. I run the code below (from the command line on Windows 7) and it works as expected:

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);
}

so your problem is not with that code. It may be somewhere else in your code or due to the permissions on the files/folder you are using.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top