Utility Classes of The JDK - Dealing With I - O PDF

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

Sign in Get started

ARCHIVE WRIT E FOR US S T YLE GUIDE ABOUT JOB BOARD

You have 2 free stories left this month. Sign up and get an extra one for free.

Utility Classes of the JDK: Dealing


With I/O
Easier le operations with over 60 helper methods
Ben Weidig Follow
Mar 26 · 3 min read

Photo by Maksym Kaharlytskyi on Unsplash

Java NIO (“non-blocking I/O”) is a great feature set for dealing with I/O
operations, introduced by Java 1.4. It was further improved in Java 7
(JSR 203). This release also brought us the two utility classes of this
article: java.nio.file.Files and java.nio.file.Paths

At least Java 8 is assumed. All listed methods omit the static keyword, and
generic type information might be simplified to reduce visual clutter and
improve readability. Every method is linked to the Java Platform SE 8
documentation provided by Oracle.

. . .

The Path Interface


The core of many I/O operations is the java.nio.file.Path interface. It
represents a hierarchical sequence of directories and file name
elements, which may be used for locating a file or directory, with a
system-dependent file path separator.

It’s mostly interoperable with java.io.File . Both types offer conversion


methods: File#toPath() and Path#toFile() .

. . .

java.nio.file.Paths
The java.nio.file.Paths isn’t a “full-fledged” utility class with lots of
different methods. It’s a mere helper for creating a java.nio.file.Path

instance:

Path get(String first,


String... more)

Path get(URI uri)

Instead of needing to concatenate Strings of directories and filenames,


we can use this helper instead. The appropriate filesystem separator will
be used:

Paths.get("data", "logs", "error")


// => data/logs/error

. . .

java.nio.file.Files
The java.nio.file.Files utility class is a behemoth. In Java 8, it consists
of 65 static methods. The latest LTS, Java 11, upped the number to 69.

Some listed methods appear in multiple sections, if appropriate.

java.nio.file.OpenOption
We can influence how files are opened by providing one or more
java.nio.file.OpenOption . There are multiple options available, defined
in java.nio.file.StandardOpenOption :

APPEND

CREATE

CREATE_NEW — Fail if it already exists

DELETE_ON_CLOSE

DSYNC — Requires that synchronous content writes to storage

READ

SPARSE

SYNC — Require synchronous writes of content and metadata to


storage

TRUNCATE_EXISTING

WRITE

Creating files and directories


Different kinds of filesystem objects can be created easily:

There are also special methods for dealing with temporary objects. They
will create a file or directory in the default temporary-file directory, with
a randomized name. But we can provide a prefix/suffix for better
identification:

We can also create a file by using a


java.nio.channels.SeekableByteChannel by using the appropriate
java.nio.file.OpenOption :

Reading content
Content reading can be categorized into two groups: byte-based and
character-based.

Both categories are filled with methods for reading “all-at-once”, or “on-
demand/lazy”.

Byte-based

Character-based

Writing
Like reading, writing content can be separated into two groups:

Byte-based

Character-based

Directory content
There are three different kinds of iterating/walking over directory
content:

java.nio.file.DirectoryStream — A specialized java.lang.Iterable .

java.util.stream.Stream — Use the more modern Stream API.

java.nio.file.FileVisistor — Use the visitor pattern.

Each one has its merits, depending on our requirements.

When walking over a Path , we can specify java.nio.file.FileVisitOption .

At this point, only FOLLOW_LINKS is available. If a cycle is detected, a


FileSystemLoopException is thrown.

There are two additional methods for listing/finding directory content:

Detecting filesystem object properties


While iterating over directory content, we also want to know what we’re
dealing with.

Some methods accept java.nio.file.LinkOption , which determines how


symbolic links are handled. Only the option NOFOLLOW_LINKS is available.

Even the MIME content type can be detected:

String probeContentType(Path path)

Attributes
The usual file attributes can be read and written:

But we can also access any file attributes directly:

File operations
Last but not least, the routine file operations.

Besides java.nio.file.LinkOption , some methods use


java.nio.file.CopyOption . The available options are defined in
java.nio.file.StandardCopyOption :

ATOMIC_MOVE

COPY_ATTRIBUTES

REPLACE_EXISTING

Java 11 additions
The release of Java 11 brought us four new methods for reading/writing
Strings:

. . .

Conclusion
Another excellent utility class that simplifies a lot of complicated I/O
operations, without the need for a third-party-library.

But be aware that almost all the methods throw various exceptions!
Never trust I/O operations blindly, and always catch (and handle) their
exceptions.

. . .

Resources
java.nio.file.Paths

java.nio.file.Files

Java Non-blocking I/O (Wikipedia)

Java I/O, NIO, and NIO2 (Oracle)

Introduction to the Java NIO2 File API (Baeldung)

Utility Classes of the JDK Collections and Arrays

T hanks to Zack Shapiro.

Java Software Development Programming Android Software Engineering

71 claps

WRIT T EN BY

Ben Weidig Follow

Software developer, entrepeneur, blogger. Mostly Java,


sometimes Swift, Golang, Bash and all the other fun stu .

Better Programming Follow

Advice for programmers.

Write the rst response

More From Medium

7 Working From Home Movie Recommendation: Medium Around T he Divorcing the Narcissist
T ips to Be More Computer Chess Block: #5 Dr. Jennifer B. Rhodes in T he
E ective Right Now Kitanya Harrison Mike Dudas in T he Block Startup
Dan Silvestre in T he Startup

Am I More than Just a Finding Room for Old Patrisse Cullors Is Anatomy Of An
Piece of Meat? Baggage in a New Reshaping America Ethereum Phishing Scam
Gillian Sisley in Fearless She Relationship Bioneers in Bioneers On Facebook
Wrote Tesia Blake Mark Muskardin in Coinmonks

Discover Medium Make Medium yours Become a member


Welcome to a place where words matter. On Medium, smart Follow all the topics you care about, and we’ll deliver the Get unlimited access to the best stories on Medium — and
voices and original ideas take center stage - with no ads in best stories for you to your homepage and inbox. Explore support writers while you’re at it. Just $5/month. Upgrade
sight. Watch

About Help Legal

You might also like