Java I/O How to - Read file to byte array and save back with java.nio.file.Files








Question

We would like to know how to read file to byte array and save back with java.nio.file.Files.

Answer

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
//  ww  w . j  ava 2 s.c  om
public class Main {

  public static void main(String[] args) throws IOException {
    Path path = Paths.get("/users.txt");
    byte[] contents = Files.readAllBytes(path);

    Path newPath = Paths.get("/newUsers.txt");

    Files.write(newPath, contents, StandardOpenOption.CREATE);

  }
}