Java Streams   «Prev  Next»

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

FileInputStream and FileOutputStream constructors in Java 17

Let us look at how you use the FileInputStream and FileOutputStream constructors. Here's an example of Java code using `FileInputStream` and `FileOutputStream` in Java SE 17. This code demonstrates how to read data from a file and write it to another file:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileCopyExample {
 public static void main(String[] args) {
     String inputFile = "input.txt";    // Source file
     String outputFile = "output.txt";  // Destination file

     // Try-with-resources statement to ensure streams are closed automatically
     try (FileInputStream fis = new FileInputStream(inputFile);
          FileOutputStream fos = new FileOutputStream(outputFile)) {

         // Buffer to hold file data
         byte[] buffer = new byte[1024];
         int bytesRead;

         // Read from input stream and write to output stream
         while ((bytesRead = fis.read(buffer)) != -1) {
             fos.write(buffer, 0, bytesRead);
         }

         System.out.println("File copied successfully!");
     } catch (IOException e) {
         System.err.println("An error occurred: " + e.getMessage());
     }
  }
}

Explanation:
  1. FileInputStream:
    • Used to read data from a file.
    • The constructor `FileInputStream(String name)` opens a connection to the file with the specified name.
  2. FileOutputStream:
    • Used to write data to a file.
    • The constructor `FileOutputStream(String name)` creates a new file or opens an existing file to write to.
  3. Try-with-resources: Introduced in Java 7, this feature ensures that resources like `FileInputStream` and `FileOutputStream` are automatically closed after the try block is exited, even if an exception is thrown.
  4. Buffer: The buffer array holds data read from the file. The `read()` method reads up to `buffer.length` bytes from the file and stores them in the buffer. The `write()` method then writes these bytes to the output file.
  5. While loop: The loop reads bytes from the input file and writes them to the output file until the end of the file is reached (`read()` returns -1).

This example demonstrates basic file handling in Java 17, which remains consistent with previous versions. The use of `try-with-resources` simplifies resource management, ensuring proper closure of streams.


Reading a file using the FileInputStream() constructor

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 using FileOutputStream() constructor

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:
FileOutputStream write() Example
The following code fragment writes the string "This program writes a string to a file named test.datat" into the file "test.data".
package com.java.bytestreams;

import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputStreamDriver {
 public static void main(String[] args) {
  try {
   FileOutputStream fos = new FileOutputStream("test.data");
   String s = "This program writes a string to a file named test.data";
   byte[] b = s.getBytes();
   for (int i = 0; i < b.length; i++) {
    fos.write(b[i]);
   }
   fos.close();
  } // end -try
  catch (IOException e) {
   System.err.println(e);
  }
 }
}

The following String will be written to the file test.data".
This program writes a string to a file named test.data

InputStream, OutputStream

A stream can be defined as a sequence of data, there are two kinds of Streams.
  1. InputStream: The InputStream is used to read data from a source.
  2. OutputStream: The OutputStream is used for writing data to a destination.

Streams consisting of Source, Program and Destination
Streams consisting of Source, Program and Destination

Java provides flexible support for I/O related to files and networks. This page discusses very basic functionality related to streams and I/O.
Byte Streams
Java Byte Streams are used to perform input and output of 8-bit bytes. Although there are many classes related to byte streams, the most frequently used classes are:
  1. FileInputStream and
  2. FileOutputStream.

Executing the Java Class
The following example makes use of two classes to copy an input file to an output file.
1. Running CopyFile.java from Eclipse
When running the following file in Eclipse, make sure the file "input.txt" is at the same level as your 1) bin and 2) src folders. Let us use a file input.txt with the following content.
This is test for copy file.
package com.java.bytestreams;
import java.io.*;

public class CopyFile {
 public static void main(String args[]) throws IOException   {
   FileInputStream in = null;
   FileOutputStream out = null;
   try {
      in = new FileInputStream("input.txt");
      out = new FileOutputStream("output.txt");
      
      int c;
      while ((c = in.read()) != -1) {
         out.write(c);
      }
   }finally {
      if (in != null) {
         in.close();
      }
      if (out != null) {
         out.close();
      }
   }
 }
}

1. Running CopyFile.java from the Command Prompt
a) Compile the above program.
Put the above code in CopyFile.java file and execute the following from the command line on Unix or Linux machine.
$javac CopyFile.java

b) Execute CopyFile.java, which will result in creating the output.txt file with the same content as the "input.txt" file.
$java CopyFile

Java7 NIO 2

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

SEMrush Software