Java Streams   «Prev  Next»

Lesson 8Using file streams
ObjectiveWrite a program that copies files using file streams.

Using File Streams to copy Files

Let us look at how you use the FileInputStream and FileOutputStream constructors.

FileInputStream and FileOutputStream constructors in Java 11

Write example Java code using FileInputStream and FileOutputStream constructors in Java 11
In Java 11, you can use the Files.newInputStream() and Files.newOutputStream() methods to create FileInputStream and FileOutputStream instances, respectively. Here's an example code that reads data from a source file and writes it to a destination file using Java 11:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class FileCopyJava11 {

    public static void main(String[] args) {
        Path sourcePath = Path.of("source.txt");
        Path destinationPath = Path.of("destination.txt");

        try {
            copyFile(sourcePath, destinationPath);
            System.out.println("File copied successfully.");
        } catch (IOException e) {
            System.err.println("Failed to copy the file: " + e.getMessage());
        }
    }

    public static void copyFile(Path source, Path destination) throws IOException {
        try (FileInputStream fis = (FileInputStream) Files.newInputStream(source);
             FileOutputStream fos = (FileOutputStream) Files.newOutputStream(destination)) {

            int bufferSize = 8192;
            byte[] buffer = new byte[bufferSize];

            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }

        } // try-with-resources will automatically close FileInputStream and FileOutputStream
    }
}
This example is similar to the previous one but uses the Files.newInputStream() and Files.newOutputStream() methods to create FileInputStream and FileOutputStream instances. The try-with-resources statement ensures that both streams are closed automatically when the operation is complete.
The copyFile method reads data in chunks using a buffer of size 8192 bytes (8 KB) to improve efficiency, and the while loop continues until the end of the file is reached (when fis.read(buffer) returns -1). This implementation works with both text and binary files.

Reading a file

To read a file, just pass the name of the file into the FileInputStream() constructor.
Then use the read() method as normal. Java looks for files in the current working directory. Generally, this is the directory you are in when you type the name of the Java program to start running the program.

FileInputStream read() example

The following code fragment reads the file readme.txt; then types it on System.out.
try {
  FileInputStream fis = new FileInputStream("readme.txt"); 
  int n;     
  while ((n = fis.available()) > 0) {
    byte[] b = new byte[n];
    int result = fis.read(b);
    if (result == -1) break;
    String s = new String(b);
    System.out.print(s); 
  } // end while
} // end try
catch (IOException e) {
  System.err.println(e); 
}
System.out.println();

Reading a file from your C drive in Java

package com.java.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class ReadFileExample {

 public static void main(String[] args) {
  File file = new File("C:/robots.txt");
  FileInputStream fis = null;
  try {
   fis = new FileInputStream(file);
   System.out.println("Total file size to read (in bytes) :" 
   + fis.available());
    int content;
    while ((content = fis.read()) != -1) {
     // convert to char and display it
     System.out.print((char) content);
    } 
  }catch (IOException e) {
    e.printStackTrace();
  }
  finally {
   try {
    if (fis != null)
     fis.close();
    } 
   catch (IOException ex) {
    ex.printStackTrace();
   }
  }
 }
}


Writing a file

To write data to a file, just pass the name of the file into the FileOutputStream() constructor. Then use the write() methods as normal. If the file does not exist in the current working directory, it is created. If it does exist, any old data it contains is overwritten.
Instead of overwriting the old data, you can append to the file using the FileOutputStream() constructor and passing in a boolean argument in addition to the name of the file:

public FileOutputStream(String name, boolean append)
 throws IOException

When the append argument is true, data is appended to the file rather than replacing any data that already exists in the file. Applets are normally not allowed to read or write files. If your applet tries to create a FileInputStream or FileOutputStream, the constructor will throw a SecurityException.

File Streams - Exercise

Click the Exercise link below to write a program that reads two filenames from the command line and copies the first file into the second file.
File Streams - Exercise