O'Reilly logo

Core Java® Volume II—Advanced Features, Ninth Edition by Gary Cornell, Cay S. Horstmann

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

1.6.2. Reading and Writing Files

The Files class makes quick work of common file operations. For example, you can easily read the entire contents of a file:

byte[] bytes = Files.readAllBytes(path);

If you want to read the file as a string, call readAllBytes followed by

String content = new String(bytes, charset);

But if you want the file as a sequence of lines, call

List<String> lines = Files.readAllLines(path, charset);

Conversely, if you want to write a string, call

Files.write(path, content.getBytes(charset));

To append to a given file, use

Files.write(path, content.getBytes(charset), StandardOpenOption.APPEND);

You can also write a collection of lines with

Files.write(path, lines);

These simple methods are intended for dealing with text files ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required