Java java.nio.file.Files.newInputStream() Method
newInputStream() The method is used to open a file and return an input stream for reading data from that file. This is a more modern way of file operation provided by Java NIO, compared with the traditional FileInputStream, it provides better performance and richer functionality.
Method Definition
public
static
InputStream
newInputStream
(
Path path, OpenOption...
options
)
throws
IOException
Parameter Description
Path path- The path object of the file to openOpenOption... options- Optional parameter specifying how the file is opened
Return Value
Returns a new InputStream object that can be used to read data from the file
exception
IOException- If an I/O error occurs while opening the fileSecurityException- If a security manager exists and denies access to the file
Basic Usage
Example 1: The simplest file reading
Example
import
java.io.IOException
;
import
java.io.InputStream
;
import
java.nio.file.Files
;
import
java.nio.file.Path
;
import
java.nio.file.Paths
;
public
class
FilesExample
{
public
static
void
main
(
String
[
]
args
)
{
Path path
=
Paths.
get
(
"example.txt"
)
;
try
(
InputStream
inputStream
=
Files.
newInputStream
(
path
)
)
{
int
data
;
while
(
(
data
=
inputStream.
read
(
)
)
!=
1
)
{
System
.
out
.
(
(
char
)
data
)
;
}
}
catch
(
IOException
e
)
{
e.
printStackTrace
(
)
;
}
}
}
In this example, we:
- Create a
Pathobject pointing to the file to be read - Use
Files.newInputStream()method to obtain the input stream - Use the try-with-resources statement to ensure the stream is automatically closed
- Read and print the file content byte by byte
Advanced usage
Using the OpenOption parameter
OpenOption interface allows us to specify how the file is opened. The commonly used implementation class is StandardOpenOption, which provides the following options:
READ- Open the file for reading (default)WRITE- Open the file for writingAPPEND- Open the file in append modeTRUNCATE_EXISTING- If the file already exists, truncate itCREATE- Create a new file if it does not existCREATE_NEW- Create a new file, failing if the file already existsDELETE_ON_CLOSE- Delete the file when the stream is closedSPARSE- Hint the file system to create a sparse fileSYNC- Require every update to be synchronously written to storageDSYNC- Require every update to be synchronously written to storage (content only)
Example 2: Specify open options
Example
import
java.io.IOException
;
import
java.io.InputStream
;
import
java.nio.file.Files
;
import
java.nio.file.Path
;
import
java.nio.file.Paths
;
import
java.nio.file.StandardOpenOption
;
public
class
FilesExampleWithOptions
{
public
static
void
main
(
String
[
]
args
)
{
Path path
=
Paths.
get
(
"example.txt"
)
;
try
(
InputStream
inputStream
=
Files.
newInputStream
(
path,
StandardOpenOption.
READ
,
StandardOpenOption.
DSYNC
)
)
{
// Read file content...
}
catch
(
IOException
e
)
{
e.
printStackTrace
(
)
;
}
}
}
Comparison with the traditional FileInputStream
Advantages
- More modern API: Based on
Pathinterface, better integrated with other parts of NIO - More flexible: You can dynamically bind
OpenOptionSpecify multiple open modes - Better performance: In some cases better than
FileInputStreamperformance - Clearer exception handling: The thrown exception types are more specific
Disadvantages
- Java 7+: Requires Java 7 or higher
- Learning curve: Developers familiar with traditional I/O need to adapt
Best Practices
- Always use try-with-resources: Ensure that the input stream is closed properly
- Use buffering when processing large files: Consider wrapping in
BufferedInputStreamto improve performance - Check whether the file exists: You can use
Files.exists(path) - Handle Exceptionsto check whether the file exists
IOException
: Properly handle the possible
Example
import
java.io.BufferedInputStream
;
import
java.io.IOException
;
import
java.io.InputStream
;
import
java.nio.file.Files
;
import
java.nio.file.Path
;
import
java.nio.file.Paths
;
public
class
FilesBestPractice
{
public
static
void
main
(
String
[
]
args
)
{
Path path
=
Paths.
get
(
"largefile.dat"
)
;
if
(
!
Files.
exists
(
path
)
)
{
System
.
err
.
println
(
"File does not exist: "
path
)
;
return
;
}
try
(
InputStream
rawStream
=
Files.
newInputStream
(
path
)
;
BufferedInputStream
bufferedStream
=
new
BufferedInputStream
(
rawStream
)
)
{
byte
[
]
buffer
=
new
byte
[
8192
]
;
int
bytesRead
;
while
(
(
bytesRead
=
bufferedStream.
read
(
buffer
)
)
!=
1
)
{
Example 3: Best practice example
}
}
catch
(
IOException
e
)
{
System
.
err
.
println
(
// Process the read data...
e.
getMessage
(
)
)
;
}
}
}
Summary
Files.newInputStream() "Error reading file: " FileInputStream is a powerful and flexible file reading tool in Java NIO. Compared with the traditional OpenOption , it provides more features and better performance. By using
Java java.nio.file.Files