Dinga
Dinga

Reputation: 21

how can I create a folder at c:\ using Paths(not File)?

Path myFile = Paths.get("c:").resolve("folderOne").resolve("filename.txt");

Output: this creates the folderOne in the folder that the program runs but not at c:\ as hoped.

Upvotes: 2

Views: 1217

Answers (3)

Alex Shesterov
Alex Shesterov

Reputation: 27595

The fix

Use a slash or a backslash after the drive name:

    final Path path = Paths.get("c:/").resolve("folderOne").resolve("filename.txt");
    Files.createDirectories(path.getParent());

Note that a slash (c:/) works fine on Windows. A backslash works as well: Paths.get("c:\\").

Note also that Paths.get() and Path.resolve() do not create directories by themselves. You can use Files.createDirectories() to do the job.


Parsing the whole path with Paths.get()

If the path is fixed, you can parse it with Paths.get() directly — no need to call .resolve():

    final Path path = Paths.get("c:/folderOne/filename.txt");

Again, both slashes and backslashes work on Windows.


Drive-relative paths

C:, without (back)slashes creates a DRIVE_RELATIVE path — meaning that the path starts from the current folder on the given drive. A citation from https://learn.microsoft.com/en-us/dotnet/standard/io/file-path-formats

C:Projects\apilibrary\apilibrary.sln A relative path from the current directory of the C: drive.

You can see this by converting to absolute path:

System.out.println(
    Paths.get("c:").resolve("folderOne").resolve("filename.txt")
        .toAbsolutePath()
);

Links:

Upvotes: 2

Balu
Balu

Reputation: 709

You will need to import the following in your class:

import java.nio.file.Path;
import java.nio.file.Paths;

then you can use:

Path path = Paths.get("D:\\directoryName"); Files.createDirectories(path);

You also need to surround your code with a try-catch block OR you can add throws IOException like this:

public static void main(String args[]) throws IOException
{
..
}

Upvotes: 0

Sklo
Sklo

Reputation: 51

According to the Java Tutorial this would be how you create a directory in your case.

Path path = Paths.get("C:\\folderOne");
Files.createDirectories(path);

Upvotes: 1

Related Questions