Java - File Input Output Write Files

Introduction

You can use the following write() methods of the Files class to write contents to a file in one shot:

static Path write(Path path, byte[] bytes, OpenOption... options)
static Path write(Path path, Iterable<? extends CharSequence> lines, OpenOption... options)
static Path write(Path path, Iterable<? extends CharSequence> lines, Charset cs, OpenOption... options)

These methods are designed to write smaller contents to a file.

If no open options are given, it opens the file with CREATE, TRUNCATE_EXISTING, and WRITE options.

It uses a platform-dependent line separator after every line of text.

If charset is not specified when lines of text are written, UTF-8 charset is assumed.

The following code writes lines of texts to a file using the write() method.

Demo

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    // Prepare the lines of text to write in a List
    List<String> texts = new ArrayList<>();
    texts.add("one");
    texts.add("4");
    texts.add("5");
    texts.add("6");

    Path dest = Paths.get("Main.java");
    Charset cs = Charset.forName("US-ASCII");
    try {/*  w  w  w . j a v a 2s  .c o  m*/
      Path p = Files.write(dest, texts, cs, StandardOpenOption.WRITE,
          StandardOpenOption.CREATE);
      System.out.println("Text was written to " + p.toAbsolutePath());
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Result

Exercise