diff --git a/src/java.base/share/classes/java/nio/file/Files.java b/src/java.base/share/classes/java/nio/file/Files.java index 729cc7d50f516..2ff8819af1010 100644 --- a/src/java.base/share/classes/java/nio/file/Files.java +++ b/src/java.base/share/classes/java/nio/file/Files.java @@ -758,14 +758,15 @@ public static Path createDirectories(Path dir, FileAttribute... attrs) // parent may not exist or other reason } SecurityException se = null; + Path absDir = dir; try { - dir = dir.toAbsolutePath(); + absDir = dir.toAbsolutePath(); } catch (SecurityException x) { // don't have permission to get absolute path se = x; } // find a descendant that exists - Path parent = dir.getParent(); + Path parent = absDir.getParent(); while (parent != null) { try { provider(parent).checkAccess(parent); @@ -778,7 +779,7 @@ public static Path createDirectories(Path dir, FileAttribute... attrs) if (parent == null) { // unable to find existing parent if (se == null) { - throw new FileSystemException(dir.toString(), null, + throw new FileSystemException(absDir.toString(), null, "Unable to determine if root directory exists"); } else { throw se; @@ -787,7 +788,7 @@ public static Path createDirectories(Path dir, FileAttribute... attrs) // create directories Path child = parent; - for (Path name: parent.relativize(dir)) { + for (Path name: parent.relativize(absDir)) { child = child.resolve(name); createAndCheckIsDirectory(child, attrs); } diff --git a/test/jdk/java/nio/file/Files/CreateDirectories.java b/test/jdk/java/nio/file/Files/CreateDirectories.java index f49251458c7e8..e3204192cdcbd 100644 --- a/test/jdk/java/nio/file/Files/CreateDirectories.java +++ b/test/jdk/java/nio/file/Files/CreateDirectories.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 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 @@ -32,7 +32,7 @@ /* * @test - * @bug 8032220 8293792 + * @bug 8032220 8293792 8307976 * @summary Test java.nio.file.Files.createDirectories method * @library .. * @run testng CreateDirectories @@ -91,7 +91,8 @@ public void testSymlinkDir() throws Exception { public void testCreateDirectories() throws IOException { final Path tmpdir = TestUtil.createTemporaryDirectory(); // a no-op - Files.createDirectories(tmpdir); + Path d = Files.createDirectories(tmpdir); + assertTrue(d == tmpdir, d + " != " + tmpdir); // create one directory Path subdir = tmpdir.resolve("a"); @@ -120,5 +121,10 @@ public void testCreateDirectories() throws IOException { Path root = Path.of("/"); Files.createDirectories(root); Files.createDirectories(root.toAbsolutePath()); + + // the returned path should not be absolute + Path temp = Path.of(".temp/temp.abc/temp.def"); + Path a = Files.createDirectories(temp); + assertTrue(a == temp, a + " != " + temp); } }