Use java.nio.file.Paths.get (String first, String ... more)
.
Path path = Paths.get("/var/temp/sample.csv");
Path path2 = Paths.get("/", "var","temp","sample.csv");
The path dividers ('/' on Unix and'' on Windows) are good for the Java side.
The above /var/temp/sample.csv
will interpret the drive where the application is running as the root directory on Windows.
For example, if you are running your application somewhere on your C: drive, the above example would be C: \ var \ temp \ sample.csv
.
From Java 11, you can use java.nio.file.Path.of (String first, String ... more)
.
// Java11
Path path = Path.of("/var/temp/sample.csv");
Use the Path.resolve (Path other)
method.
Path parent = Paths.get("/var/temp");
Path child = Paths.get("child");
Path file = Paths.get("sample.csv");
Path connected = parent.resolve(child).resolve(file); // -> /var/temp/child/sample.csv
When creating a Path instance using Paths.get (String first, String ... more)
, starting with /
will be considered as the path from the root directory.
So if you inadvertently write code like the following, it won't work.
// /var/temp/I want to make a child
Path parent = Paths.get("/var/temp");
Path child = Paths.get("/child"); // "/"It is considered to be the path from the root directory because it starts with
Path connected = parent.resolve(child); // -> /temp
Path→File
Use the Path.toFile ()
method.
Path path = Paths.get("/var/temp");
File file = path.toFile();
File→Path
Use the File.toPath ()
method.
File file = new File("/var/temp");
Path path = file.toPath();
Recommended Posts