Course contentsShow
← Java
Lesson 2039 of 2,87041. NIO.2 and the Path APIFree lesson

Writing Lines: Files.write with Iterable<CharSequence>

Write a collection of strings to a file line-by-line using Files.write with an Iterable.

Writing Lines: Files.write with Iterable<CharSequence>

What you'll learn: How to write a collection of strings to a file line-by-line in a single method call using Files.write.

The Convenience of Writing Line Collections

You've already seen Files.write with a byte array to write raw data. NIO.2 also provides an overloaded version that accepts an Iterable<? extends CharSequence> — meaning you can pass any collection of strings (or any character sequence) and write them as lines to a file, automatically.

Think of it like handing a stack of index cards to someone who writes each card's contents on a separate line in a notebook. You don't worry about line separators or encoding details — Files.write handles it for you.

How It Works

List<String> lines = Arrays.asList(
    "First line of text",
    "Second line of text",
    "Third line of text"
);

Path outputPath = Paths.get("output.txt");
Files.write(outputPath, lines, StandardCharsets.UTF_8);

Behind the scenes, Files.write iterates through your collection, writes each string, and appends the platform's line separator after each one. You specify the charset (like UTF_8) to control character encoding.

Key Options

You can also pass StandardOpenOption values to control behavior:

// Append instead of overwriting
Files.write(outputPath, lines, StandardCharsets.UTF_8, 
            StandardOpenOption.APPEND);

This method is perfect when you have a List, Set, or any Iterable of strings ready to write. It's cleaner and more concise than manually looping with BufferedWriter or PrintWriter.

Key Takeaway: Use Files.write(Path, Iterable<CharSequence>, Charset) to write a collection of strings as lines to a file in one convenient call, with automatic line separator handling and charset control.