NIO 2 File API

From NovaOrdis Knowledge Base
Revision as of 06:23, 2 April 2021 by Ovidiu (talk | contribs) (→‎Recipes)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

External

Internal

Subjects

Recipes

Build a new absolute Path instances from components:

Path p = Paths.get("/Users", "ovidiu", "tmp")

Build a new relative Path instances from components:

Path p = Paths.get("ovidiu", "tmp")

To research:

Path.of("")

Create one directory:

Path parent = ...;
Path dir = Files.createDirectory(Paths.get(parent.toString(), "my-dir"));

Create a directory hierarchy:

Path parent = ...;
Path dir = Files.createDirectories(Paths.get(parent.toString(), "dir1/dir2/dir3"));

Get file name:

Path file = ...;
String fileName = file.getFileName().toString();

Create a file with a specified content:

Path file = ...;
Files.write(file, "something".getBytes());

Verify that a directory exists (works for both absolute and relative paths)

Path p = Paths.get("/Users/ovidiu/tmp");
assert Files.isDirectory(p) == true
// run from "/Users"
Path p = Paths.get("ovidiu/tmp");
assert Files.isDirectory(p) == true

Get current directory:

new File(".").toPath().toAbsolutePath().toString()