8317128: java/nio/file/Files/CopyAndMove.java failed with AccessDeniedException

Reviewed-by: alanb, lancea
This commit is contained in:
Brian Burkhalter 2023-10-06 17:46:03 +00:00
parent b62e774e6a
commit 6c6beba256
2 changed files with 18 additions and 14 deletions

View File

@ -25,9 +25,13 @@
package java.nio.file;
import java.nio.file.attribute.*;
import java.io.InputStream;
import java.io.IOException;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.spi.FileSystemProvider;
/**
* Helper class to support copying or moving files when the source and target
@ -69,14 +73,6 @@ class CopyMoveHelper {
}
return result;
}
CopyOption[] replaceExistingOrEmpty() {
if (replaceExisting) {
return new CopyOption[] { StandardCopyOption.REPLACE_EXISTING };
} else {
return new CopyOption[0];
}
}
}
/**
@ -137,14 +133,22 @@ class CopyMoveHelper {
if (sourceAttrs.isSymbolicLink())
throw new IOException("Copying of symbolic links not supported");
// ensure source can be copied
FileSystemProvider provider = source.getFileSystem().provider();
provider.checkAccess(source, AccessMode.READ);
// delete target if it exists and REPLACE_EXISTING is specified
if (opts.replaceExisting)
Files.deleteIfExists(target);
else if (Files.exists(target))
throw new FileAlreadyExistsException(target.toString());
// create directory or copy file
if (sourceAttrs.isDirectory()) {
if (opts.replaceExisting)
Files.deleteIfExists(target);
Files.createDirectory(target);
} else {
try (InputStream in = Files.newInputStream(source)) {
Files.copy(in, target, opts.replaceExistingOrEmpty());
Files.copy(in, target);
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2008, 2016, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2008, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -31,7 +31,7 @@ import java.io.IOException;
import static sun.nio.fs.WindowsConstants.*;
/**
* Internal exception thrown when a Win32 calls fails.
* Internal exception thrown when a Win32 call fails.
*/
class WindowsException extends Exception {