Java java.nio.file.Files.newInputStream()Method
newInputStream()This method is used to open a file and returns an input stream to read data from the file. It is a more modern file operation method provided by Java NIO. Compared to the traditionalFileInputStream, it provides better performance and richer functionality.
Method Definition
throws IOException
Parameter Description
Path path- The path object of the file to be openedOpenOption... options- Optional parameter, specifies how the file is opened
Return Value
Returns a newInputStreamobject, which can be used to read data from the file
Exceptions
IOException- If an I/O error occurs when opening the fileSecurityException- If a security manager exists and denies access to the file
Basic Usage
Example 1: Simplest File Reading
Example
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.print((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 get the input stream - Use a try-with-resources statement to ensure the stream is automatically closed
- Read file content byte by byte and print it
Advanced Usage
Using the OpenOption Parameter
OpenOptionThe interface allows us to specify how the file is opened. The commonly used implementation class isStandardOpenOption, it provides the following options:
READ- Opens the file for reading (default)WRITE- Opens the file for writingAPPEND- Opens the file for appendingTRUNCATE_EXISTING- Truncates the file if it already existsCREATE- Creates a new file if it does not existCREATE_NEW- Creates a new file, and fails if the file already existsDELETE_ON_CLOSE- Deletes the file when the stream is closedSPARSE- Hints the file system to create a sparse fileSYNC- Requires every update to be synchronously written to storageDSYNC- Requires every update to be synchronously written to storage (content only)
Example 2: Specifying Open Options
Example
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 Traditional FileInputStream
Advantages
- More modern API: Based on
Pathinterface, better integrated with other parts of NIO - More flexible: Can
OpenOptionspecify multiple opening modes - Better performance: In some cases, compared to
FileInputStreamperformance is better - Clearer exception handling: The types of exceptions thrown 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 the input stream is properly closed
- Use buffering when handling large files: Consider wrapping it in
BufferedInputStreamto improve performance - Check if the file exists: Before attempting to open, you can use
Files.exists(path) - Handle exceptions: Properly handle possible
IOException
Example 3: Best Practice Example
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 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) {
// Process the read data...
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}
}
}
Summary
Files.newInputStream()is a powerful and flexible file reading tool in Java NIO. Compared to the traditionalFileInputStreamit provides more features and better performance. By usingOpenOptionparameters and following best practices, you can write efficient and reliable file reading code.
Java java.nio.file.Files