«Back to Home

Core Java

Topics

File Handling In Java

File Handling
 
In Java File handling, FileInputStream and FileOutputStream classes are used.
 
In Java, Byte streams are used to perform input and output of 8-bit bytes. While there are many classes related to byte streams but commonly used classes are FileInputStream and FileOutputStream.
 
FileOutputStream class

FileOutputStream is an output stream, which is used to write the data to a file.
 
We can write byte-oriented as well as character-oriented data. If we want to write primitive values, we need to use FileOutputStream.
 
Let’s see an example, given below.
 
Code
  1. import java.io.*;  
  2. public class FileHandlingExample {  
  3.     public static void main(String args[]) {  
  4.         try {  
  5.             FileOutputStream fos = new FileOutputStream("Java.txt");  
  6.             String s1 = "Java is a object oriented programing language";  
  7.             byte b[] = s1.getBytes(); //convert string into byte array  
  8.             fos.write(b);  
  9.             fos.close();  
  10.             System.out.println("Run successfully.....");  
  11.         } catch (Exception e) {  
  12.             System.out.println(e);  
  13.         }  
  14.     }  
  15. }  
4

Output

5
 
FileInputStream class

FileInputStream class obtains input bytes from a file. It is used to read streams of raw bytes such as read image, audio, video etc.
 
Let’s see an example, given below.
 
Code
  1. import java.io.*;  
  2. public class FileHandlingExample {  
  3.     public static void main(String args[]) {  
  4.         try {  
  5.             FileInputStream fis = new FileInputStream("Java.txt");  
  6.             int i = 0;  
  7.             while ((i = fis.read()) != -1) {  
  8.                 System.out.print((char) i);  
  9.             }  
  10.             fis.close();  
  11.         } catch (Exception e) {  
  12.             System.out.println(e);  
  13.         }  
  14.     }  
  15. }  
6

Output

7
 
 
Now let’s see another example to read the data of current Java file and write it into another file.
 
Code
  1. import java.io.*;  
  2. public class FileHandlingExample {  
  3.     public static void main(String args[]) throws Exception {  
  4.         FileInputStream fis = new FileInputStream("Simple.java");  
  5.         FileOutputStream fos = new FileOutputStream("Example.java");  
  6.         int i = 0;  
  7.         while ((i = fis.read()) != -1) {  
  8.             fos.write((byte) i);  
  9.         }  
  10.         fis.close();  
  11.     }  
  12. }  
8

In the example, mentioned above, we are reading the data of Simple.java file and write it into Example.java file.
 
Summary

Thus, we learnt that Java FileInputStream and FileOutputStream classes are used in Java file handling and also learnt how we can use these classes in Java.