Java java.nio.file.Files.newInputStream()Method

Java File Java java.nio.file.Files


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

public static InputStream newInputStream(Path path, OpenOption... options)
    throws IOException

Parameter Description

  1. Path path- The path object of the file to be opened
  2. OpenOption... 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 file
  • SecurityException- If a security manager exists and denies access to the file

Basic Usage

Example 1: 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.print((char) data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this example, we:

  1. Create aPathobject pointing to the file to be read
  2. UseFiles.newInputStream()method to get the input stream
  3. Use a try-with-resources statement to ensure the stream is automatically closed
  4. 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 writing
  • APPEND- Opens the file for appending
  • TRUNCATE_EXISTING- Truncates the file if it already exists
  • CREATE- Creates a new file if it does not exist
  • CREATE_NEW- Creates a new file, and fails if the file already exists
  • DELETE_ON_CLOSE- Deletes the file when the stream is closed
  • SPARSE- Hints the file system to create a sparse file
  • SYNC- Requires every update to be synchronously written to storage
  • DSYNC- Requires every update to be synchronously written to storage (content only)

Example 2: Specifying 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 Traditional FileInputStream

Advantages

  1. More modern API: Based onPathinterface, better integrated with other parts of NIO
  2. More flexible: CanOpenOptionspecify multiple opening modes
  3. Better performance: In some cases, compared toFileInputStreamperformance is better
  4. Clearer exception handling: The types of exceptions thrown are more specific

Disadvantages

  1. Java 7+: Requires Java 7 or higher
  2. Learning curve: Developers familiar with traditional I/O need to adapt

Best Practices

  1. Always use try-with-resources: Ensure the input stream is properly closed
  2. Use buffering when handling large files: Consider wrapping it inBufferedInputStreamto improve performance
  3. Check if the file exists: Before attempting to open, you can useFiles.exists(path)
  4. Handle exceptions: Properly handle possibleIOException

Example 3: Best Practice Example

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) {
                // 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 File Java java.nio.file.Files

Other Extensions