GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • java.evolved
  • โ†
  • โ†’

This view

  • Original page
  • New address

GeezerVison is showing javaevolved.dev โ€” Path.of() factory | java.evolved

Home / I/O / Path.of() factory
I/O Beginner

Path.of() factory

  • ๐Ÿ› Report a code issue
  • ๐ŸŒ Report a translation issue
  • ๐Ÿ’ก Suggest a new pattern

Use Path.of() โ€” the modern factory method on the Path interface.

I/O
Code Comparison
โœ• Java 8
Path path = Paths.get("src", "main",
    "java", "App.java");
โœ“ Java 11+
var path = Path.of("src", "main",
    "java", "App.java");
Share ๐•
See a problem with this code? Let us know.
Why the modern way wins
๐Ÿ“

Consistent API

Follows the .of() factory pattern like List.of(), Set.of().

๐Ÿ“–

Discoverable

Found on the Path type itself, not a separate Paths class.

๐Ÿงน

One less class

No need to import the Paths utility class.

Old Approach
Paths.get()
Modern Approach
Path.of()
Since JDK
11
Difficulty
Beginner
JDK Support
Path.of() factory
Available

Widely available since JDK 11 (Sept 2018)

How it works

Path.of() is a factory method added directly to the Path interface, replacing the separate Paths utility class. It's more discoverable and consistent with List.of(), Map.of(), etc.

Related Documentation
Path.of() โ†—
Proof
View proof source โ†—
Related patterns
I/O Beginner

InputStream.transferTo()

Java 8
byte[] buf = new byte[8192];
int n;
while ((n = input.read(buf)) != -1) {
    output.write(buf, 0, n);
}
Java 9+
input.transferTo(output);
Hover to see modern โžœ
JDK 9+ โ†’
I/O Beginner

Reading files

Java 8
StringBuilder sb = new StringBuilder();
try (BufferedReader br =
    new BufferedReader(
        new FileReader("data.txt"))) {
    String line;
    while ((line = br.readLine()) != null)
        sb.append(line).append("\n");
}
String content = sb.toString();
Java 11+
String content =
    Files.readString(Path.of("data.txt"));
Hover to see modern โžœ
JDK 11+ โ†’
I/O Beginner

Try-with-resources improvement

Java 8
Connection conn = getConnection();
// Must re-declare in try
try (Connection c = conn) {
    use(c);
}
Java 9+
Connection conn = getConnection();
// Use existing variable directly
try (conn) {
    use(conn);
}
Hover to see modern โžœ
JDK 9+ โ†’
You are visitor 01402503 โ€” GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800ร—600. No cookies required.