Java IO & NIO - Files.newInputStream() 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 InputStream newInputStream(Path path,
                                         OpenOption... options)
                                  throws IOException

Opens a file, returning an input stream to read from the file.

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


Examples


package com.logicbig.example.files;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Scanner;

public class NewInputStreamExample {

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

try (InputStream inputStream = Files.newInputStream(path)) {
String s = inputStreamToString(inputStream);
System.out.println(s);
}
}

public static String inputStreamToString(InputStream inputStream) {
//In Java 9 use inputStream.readAllBytes()
return new Scanner(inputStream,
"UTF-8").useDelimiter("\\A").next();
}
}

Output

test content...




See Also