Java IO & NIO - Files.write() Examples

Code Snippets Java IO & NIO Java 


Class:

java.nio.file.Files

java.lang.Objectjava.lang.Objectjava.nio.file.Filesjava.nio.file.FilesLogicBig

Methods:

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

Writes bytes to a file.

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


public static Path write(Path path,
                         Iterable<? extends CharSequence> lines,
                         OpenOption... options)
                  throws IOException
public static Path write(Path path,
                         Iterable<? extends CharSequence> lines,
                         Charset cs,
                         OpenOption... options)
                  throws IOException
Parameters:
path - the path to the file
lines - an object to iterate over the char sequences
cs - the charset to use for encoding
options - options specifying how the file is opened
Returns:
the path



Examples


package com.logicbig.example.files;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class WriteExample {

public static void main(String... args) throws IOException {
Path path = Files.createTempFile("test-file", ".txt");
Files.write(path, "some test content...".getBytes());

byte[] bytes = Files.readAllBytes(path);
System.out.println(new String(bytes));
}
}

Output

some test content...




package com.logicbig.example.files;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;

public class WriteExample2 {

public static void main(String... args) throws IOException {
Path path = Files.createTempFile("test-file", ".txt");
Iterable<String> iterable = Arrays.asList("line1", "line2");
Files.write(path, iterable);

byte[] bytes = Files.readAllBytes(path);
System.out.println(new String(bytes));

}
}

Output

line1
line2




See Also