Java IO & NIO - Files.newOutputStream() Examples

Code Snippets Java IO & NIO Java 


Class:

java.nio.file.Files

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

Method:

public static OutputStream newOutputStream(Path path,
                                           OpenOption... options)
                                    throws IOException

Opens or creates a file, returning an output stream that may be used to write bytes to the file.

Parameters:
path - the path to the file to open or create
options - options specifying how the file is opened
Returns:
a new output stream


Examples


package com.logicbig.example.files;

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

public class NewOutputStreamExample {

public static void main(String... args) throws IOException {
Path path = Files.createTempFile("test-file", ".txt");
System.out.println("-- writing to file --");
try (OutputStream outputStream = Files.newOutputStream(path)) {
outputStream.write("test file content....".getBytes());
}

System.out.println("-- reading from file --");
Files.readAllLines(path)
.forEach(System.out::println);
}
}

Output

-- writing to file --
-- reading from file --
test file content....




See Also