5

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?

Silver Quettier
  • 2,045
  • 2
  • 26
  • 53
  • As a test, can you write to target instead of temp? What does `getCurrentConfigFile` do? Maybe it opens the file without closing it? – assylias Apr 01 '14 at 08:01
  • @assylias I edited my question to add details about `getCurrentConfigFile()`. I don't think it's linked to the problem thus. Writing directly to the target works. Maybe my try block is too wide, and the problem lies in fact in reading the temp file. – Silver Quettier Apr 01 '14 at 08:20

1 Answers1

2

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.

assylias
  • 321,522
  • 82
  • 660
  • 783
  • Thank you for your efforts. This is not good news thus, as code problems, I can fix, the rest, I'm not sure! I will try to circumvent the issue by using my own temporary directory. – Silver Quettier Apr 01 '14 at 08:41
  • 2
    After some code spelunking, I found a `BufferedReader` which was not properly closed on that file, in some other class called before. I'll accept your "long comment" as the answer to my problem: "Your code is fine, search elsewhere." – Silver Quettier Apr 01 '14 at 09:22