java files

Java byte array to file

public static Path write(Path path,byte[] bytes,OpenOption… options)
throws IOException

Writes bytes to a file. The options parameter specifies how the the file is created or opened. If no options are present then this method works as if the CREATE, TRUNCATE_EXISTING, and WRITE options are present. In other words, it opens the file for writing, creating the file if it doesn’t exist, or initially truncating an existing regular-file to a size of 0. All bytes in the byte array are written to the file. The method ensures that the file is closed when all bytes have been written (or an I/O error or other runtime exception is thrown). If an I/O error occurs then it may do so after the file has created or truncated, or after some bytes have been written to the file.
Usage example: By default the method creates a new file or overwrites an existing file. Suppose you instead want to append bytes to an existing file:

 Path path = ...
 byte[] bytes = ...
 Files.write(path, bytes, StandardOpenOption.APPEND);

Parameters:
path – the path to the file
bytes – the byte array with the bytes to write
options – options specifying how the file is opened
Returns:
the path
Throws:
IOException – if an I/O error occurs writing to or creating the file
UnsupportedOperationException – if an unsupported option is specified
SecurityException – In the case of the default provider, and a security manager is installed, the checkWrite method is invoked to check write access to the file.

package com.candidjava.file;

import java.io.File;
import java.io.FileWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class JavaByteArrayToFile {
  public static void main(String[] args)throws Exception {
    Path path=Paths.get("F:/Files/writeByte.txt");
    byte b[]=new byte[]{10,20,30,40};
    System.out.println(b);
    Path p1=Files.write(path, b, StandardOpenOption.APPEND);
    System.out.println(p1);
  }

}