Write to a File using Java Stream API

package org.code2care.streams;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.stream.Stream;

public class WriteToFileStreamAPIExample {

    public static void main(String[] args) {

        String line1 = "This is line 1.";
        String line2 = "This is line 2.";
        String line3 = "This is line 3.";
        String line4 = "This is line 4.";

        Stream<String> stream = Stream.of(line1, line2, line3, line4);

        String fileName = "myfile.txt";
        Path filePath = Path.of(fileName);

        try {
            Iterable<String> iterable = stream::iterator;
            Files.write(filePath, iterable, StandardOpenOption.CREATE);
        } catch (IOException e) {
            System.out.println("Error while writing to file: " + e.getMessage());

File was written using Java Stream API

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap