FileInputStream and FileOutputStream in Java

"

Introduction to FileInputStream and FileOutputStream Classes in Java

FileInputStream and FileOutputStream are two of the most important classes in the Java programming language for reading and writing data to files, respectively. They are both byte streams, which means that they read and write data in binary format, consisting of exactly 8-bit bytes.

FileInputStream is used to read data from a file, one byte at a time.To create a FileInputStream object, you must pass the path to the file you want to read as a constructor argument.

FileOutputStream is used to write data to a file, one byte at a time. It can be used to write any type of file, including text files, image files, and audio files. To create a FileOutputStream object, you must pass the path to the file you want to write to as a constructor argument.

FileInputStream and FileOutputStream are very powerful classes for reading and writing data to files in Java. They are used in a wide variety of applications, including text editors, image viewers, and audio players.

  • Both FileInputStream and FileOutputStream are subclasses of the InputStream and OutputStream classes, respectively. This means that they inherit all of the methods from these parent classes.
  • FileInputStream and FileOutputStream are both AutoCloseable classes. This means that they can be automatically closed using the try-with-resources statement.
  • If you are writing to a file that does not exist, FileOutputStream will create the file for you.
  • If you are writing to a file that already exists, FileOutputStream will overwrite the contents of the file.
  • To append data to an existing file, you can use the FileOutputStream constructor that takes a boolean parameter. If you set this parameter to true, FileOutputStream will append data to the end of the file instead of overwriting it.
Methods of FileInputStream Class
Method Description
available() Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking, which may be 0, or 0 when end of stream is detected.
close() Closes this input stream and releases any system resources associated with the stream.
mark(int readlimit) Marks the current position in this input stream. A subsequent reset() will attempt to reposition the stream to this point.
markSupported() Tells whether this input stream supports the mark() and reset() methods.
read() Reads a byte of data from this input stream.
read(byte[] b) Reads up to b.length bytes of data from this input stream into an array of bytes.
read(byte[] b, int off, int len) Reads up to len bytes of data from this input stream into an array of bytes, starting at offset off in the array.
reset() Repositions this stream to the position at which the last mark() was set.
skip(long n) Skips over and discards n bytes of data from this input stream.
Methods of FileOutputStream Class
Method Description
close() Closes this output stream and releases any system resources associated with this stream.
flush() Flushes this output stream and forces any buffered output bytes to be written out to the underlying device.
write(int b) Writes a byte to this output stream.
write(byte[] b) Writes b.length bytes from the specified byte array to this output stream.
write(byte[] b, int off, int len) Writes len bytes from the specified byte array starting at offset off to this output stream.
writeBytes(String s) Writes the specified string to this output stream.
writeChars(String s) Writes the specified string of characters to this output stream.
writeChars(String s, int off, int len) Writes len characters from the specified string starting at offset off to this output stream.

Exercises

Write a program to read 1 byte of data from a file


package javaprogrammingdemo;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
public class javalabclass{
  public static void main(String args[]) throws IOException{
    try
    {
      FileInputStream fs = new FileInputStream("satish.txt");
      int data=fs.read();
      System.out.print((char)data);
  fs.close();
      
    }
    catch(FileNotFoundException e)
    {
      System.out.println("Check File");
    }
}
} 

Write a program to read an Array of Bytes from a File


package javaprogrammingdemo;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
public class javalabclass{
  public static void main(String args[]) throws IOException{
    try
    {
      FileInputStream fs = new FileInputStream("satish.txt");
      byte[] input = new byte[5];
      fs.read(input);
      for(byte b:input)
      {
        System.out.print((char)b);
      }
  fs.close();
      
    }
    catch(FileNotFoundException e)
    {
      System.out.println("Check File");
    }
}
} 

Write a program to read all data from a file 1 byte at a time.


  package javaprogrammingdemo;
  import java.io.FileInputStream;
  import java.io.FileNotFoundException;
  import java.io.IOException;
  import java.util.*;
  public class javalabclass{
    public static void main(String args[]) throws IOException{
      try
      {
        FileInputStream fs = new FileInputStream("satish.txt");
        int data;
        while((data=fs.read())!=-1)
        {
          System.out.print((char)data);
        }
    fs.close();
      }
      catch(FileNotFoundException e)
      {
        System.out.println("Check File");
      }
  }
  } 

Write a program to write 1 byte of data to a file


  package javaprogrammingdemo;
  import java.io.FileInputStream;
  import java.io.FileNotFoundException;
  import java.io.FileOutputStream;
  import java.io.IOException;
  import java.util.*;
  public class javalabclass{
      public static void main(String args[]) throws IOException{
        try
        {
          //demo of Fileoutputstream
          //file gets created and data is written
          FileOutputStream fout = new FileOutputStream("output.txt");
          fout.write(104);
      fout.close();
          System.out.println("File Write Successful");
        }
        catch(FileNotFoundException e)
        {
          System.out.println("Check File");
        }
        catch(Exception e)
        {
          System.out.println("Exception Occurred");
          e.printStackTrace();
        }
    }
  } 

Write a Java Program to write an array of bytes to a file


  package javaprogrammingdemo;
  import java.io.FileInputStream;
  import java.io.FileNotFoundException;
  import java.io.FileOutputStream;
  import java.io.IOException;
  import java.util.*;
  public class javalabclass{
      public static void main(String args[]) throws IOException{
        try
        {
          //demo of Fileoutputstream
          //file gets created and data is written
          FileOutputStream fout = new FileOutputStream("output.txt");
          byte[] b = {104,105,106,107};
          fout.write(b);
      fout.close();
          System.out.println("File Write Successful");
        }
        catch(FileNotFoundException e)
        {
          System.out.println("Check File");
        }
        catch(Exception e)
        {
          System.out.println("Exception Occurred");
          e.printStackTrace();
        }
    }
  } 

Write a Java Program to append data to an Output File using FileOutputStream


  package javaprogrammingdemo;
  import java.io.FileInputStream;
  import java.io.FileNotFoundException;
  import java.io.FileOutputStream;
  import java.io.IOException;
  import java.util.*;
  public class javalabclass{
      public static void main(String args[]) throws IOException{
        try
        {
          //demo of Fileoutputstream
          //file gets created and data is written
          FileOutputStream fout = new FileOutputStream("output.txt",true);
          byte[] b = {104,105,106,107};
          fout.write(b);
      fout.close();
          System.out.println("File Write Successful");
        }
        catch(FileNotFoundException e)
        {
          System.out.println("Check File");
        }
        catch(Exception e)
        {
          System.out.println("Exception Occurred");
          e.printStackTrace();
        }
    }
  } 

Write a Java Program that reads all data from a file and writes the data to another file. You have to read and write data 1 byte at a time.


  package javaprogrammingdemo;
  import java.io.FileInputStream;
  import java.io.FileNotFoundException;
  import java.io.FileOutputStream;
  import java.io.IOException;
  import java.util.*;
  public class javalabclass{
      public static void main(String args[]) throws IOException{
        try
        {
          //reading data from a file an writing to another file
          FileInputStream fin = new FileInputStream("satish.txt");
          FileOutputStream fout = new FileOutputStream("output.txt",true);
          int data;
          while((data=fin.read())!=-1)
          {
            fout.write(data);
          }
          System.out.println("File Write Completed");
          fin.close();
          fout.close();
        }
        catch(FileNotFoundException e)
        {
          System.out.println("Check File");
        }
        catch(Exception e)
        {
          System.out.println("Exception Occurred");
          e.printStackTrace();
        }
    }
  }