Java Programming Tutorials

Java programming tutorials with many code examples!

Java 8 write to a text file

Problem:

How to write to a text file in Java 8?

Solution:

In Java 8 use Files and Paths and using try-with-resources construct.

package com.farenda.solved;

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class JavaSolved {
    public static void main(String[] args) throws IOException {
        String file = "languages.txt";
        System.out.println("Writing to file: " + file);
        // Files.newBufferedWriter() uses UTF-8 encoding by default
        try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(file))) {
            writer.write("Java\n");
            writer.write("Python\n");
            writer.write("Clojure\n");
            writer.write("Scala\n");
            writer.write("JavaScript\n");
        } // the file will be automatically closed
    }
}

Result:

$> cat languages.txt
Java
Python
Clojure
Scala
JavaScript

Java 8 simplifies working with files so much!

Share with the World!
  • firstpostcommenter

    file writer using java8