tips for java.nio.file.Path

Instance Path from a string

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");

Connect the paths

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

Mutual conversion with java.io.File

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

tips for java.nio.file.Path
Gradle TIPS collection (for myself)
[Java] Tips for writing source
Tips for making APIs generic
Tips for handling enums in thymeleaf
Tips for handling pseudo-elements in Selenium
Java tips, tips
Tips for gRPC error handling in Ruby
Interoperability tips with Kotlin for Java developers
Rails Tips
Java Tips
Tips for using the Spotify app on Ubuntu
Tips for improving Jbuilder rendering time with jsonapi-serializer
Tips for googled Domain Driven Design related information
Tips for testing with mock for classes using @value
3 Tips to Improve Lead Time for Docker Build
Tips for generating files for eclipse projects in Gradle