Reading and Writing.

Java Program to Read and Write File Using NIO newInputStream() and newOutputStream()

  • Java
  • 2 mins read

In this tutorial, I am giving examples of a Java program to read and write a file using the NIO newInputStream() and newOutputStream() methods.

You can use NIO to open input and output stream. Once you have a Path, open a file by calling newIputStream() or newOutputStream(), which are static methods defined by Files.

In Java, using NIO, open a file stream using the Files.newInputStream() method. The following is the syntax:

static InputStream newInputStream(Path path, OpenOption...how)
            throws IoException

Read a File in Java Using NIO newInputStream() Example

The following Java program takes an argument for a filename; then it will read the file and print the contents on the screen using the newInputStream() NIO method.

ShowFileContents.java

import java.io.*;
import java.nio.file.*;

class ShowFileContents {

    public static void main(String args[]) {
        int i;
        if (args.length != 1) {
            System.out.println("usage: ShowFileContents filename");
            return;
        }
        try (InputStream fin = Files.newInputStream(Paths.get(args[0]))) {
            do {
                i = fin.read();
                if (i != -1) {
                    System.out.print((char) i);
                }
            } while (i != -1);
        } catch (InvalidPathException e) {
            System.out.println("Path Error" + e);
        } catch (IOException e) {
            System.out.println("I/0 Error" + e);
        }
    }
}

Test

java ShowFileContents /user/vinish/code/temp.txt

Output

This file contains some lines.
This is the second line.
This is the last line.

To open a file for output in Java using NIO method Files.newOutputStream(). The following is the syntax:

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

Write a File in Java Using NIO newOutputStream() Example

The following java program will write the alphabets to a file named textfile.txt using the NIO newOutputStream() method.

NIOWriteFile.java

import java.io.*;
import java.nio.file.*;

class NIOWriteFile {

    public static void main(String args[]) 
    {
        try (OutputStream fout = 
                new BufferedOutputStream(
                        Files.newOutputStream(Paths.get("//user//vinish//code//testfile.txt")))) 
        {
            for (int i=0; i < 26; i++)
                fout.write((byte) ('A' + i));
            
        } catch(InvalidPathException e) {
            System.out.println("Path Error" + e);
        } catch (IOException e) {
            System.out.println("I/O Error: " + e);
        }
    }
}

You can find the file textfile.txt at the specified location.

See also: