File Handling Java source code : Reading , Writing and Appending to a file

File Handling in java is done by using various input and output streams . So here in this post we discuss about how we can read and write java code for reading from a file and writing to a file .
To achieve the desired goal we need to connect the file to the input stream so that , we can read the file in java .The following code helps in achieving the task

        BufferedReader bf=new BufferedReader(new FileReader(abc.txt));


To write to the file in java we need to connect the output stream to the file so that the output will be shown in a proper format . The following code helps in achieving the task

         FileWriter    f0 = new FileWriter(f,false);
       // here f passed to the arguments is a file object to which we write the content .

Here we use BufferedWriter instead of PrintWriter , we can use any of them , but then the obvious question is what is the difference between BufferedWriter and PrintWriter . BufferedWriter and PrintWriter both
write  line by line . But bufferedwriter do it in the same line while printwriter in different line.

There are two types of streams in the I/O .these are

High Level Streams :  These streams are directly connected to the other streams and they are not connected
                                  to  any of the input output devices.

Low level Streams   :  These streams are directly connected to the input /output devices of the system .

Example of the high level streams :  Buffered,Data Reader/Writer are high level streams .  

Now in  the below code , we have done  overriding content in the file and appending in the same class that is JavaFileHandlingExample.java while the reading of the file has been done by creating a new class named as FReading .

We use Scanner class to read input from the console . Scanner class is found in the java.util package . The Scanner class nextLine() method helps in reading the line from the console . The method nextLine() return type is string . So we do not need to make any changes in the return value of the nextLine() method of the Scanner class.

Here to delete a file we use the delete() method  whose function is (as you guessed correctly ) to delete the file , it is one of the most important methods to remember . This function is found in the File class .

There is also another method named createNewFile() which is used to create a blank file (file without content) with the file name passed in the File object as the string .

To read the file till end , we need to use the while loop

//For reading till end
            while((str=bf.readLine())!=null)


To append lines in the file we use the append() method of the filewriter class .

There is one important practice one should keep in mind while using scanner class is to flush the stream .
By calling flush() method on the scanner class object .

Pseudo Code : 

1.  Select operation to read,write or append
2. User inputs some strings in the file , and continues till user inputs stop string
3. If  read
             check whether the file exists or not
             if exists
                then read all the lines and print it in the console
   else if write
              if file exists
                then override the all previous content    
              else
                add lines to the file
   else if append
             if file exists then add lines to the code

Demo :

file handling write read append java






































Please find the Code below


import java.io.BufferedReader;
import java.io.File;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class JavaFileHandlingExample
{
    public static void main(String args[]) throws FileNotFoundException, IOException {
        System.out.println("Please select one of the below operations");
        System.out.println(" w for write mode ");
        System.out.println(" r for read mode ");
        System.out.println(" a for append mode ");
        Scanner in =new Scanner(System.in);
        String s=in.nextLine();
        if(s.equalsIgnoreCase("r"))
        {
            new FReading();
        }
        else if(s.equalsIgnoreCase("w")||s.equalsIgnoreCase("a"))
        {
            writingToFile(s);
            
            
        }
        else
        {
            System.out.println("Sorry you try to do unexpected ,betterluck next time ");
        }
        
        
        in.close();
        
    }
    
    public static void writingToFile(String s)
    {
        Scanner in=null;
        try
        {
            String source = "";
            File f=new File("file1.txt");
            
            BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
            //For writing new Content Everytime you run
            FileWriter f0 =null;
            if(s.equalsIgnoreCase("w"))
            {
                f0 = new FileWriter(f,false);
                System.out.println("CAUTION >> Please understand it will overwrite the content of the file ");
                System.out.println("Type 'no' to exit");
                System.out.println("Do you want to proceed :type 'yes' ");
                in=new Scanner(System.in);
                String s1=in.nextLine();
                if(s1.equals("no"))
                System.exit(0);
                System.out.println("Write 'stop' when you finish writing file ");
                f.delete();
                f.createNewFile();
                while(!(source=bf.readLine()).equalsIgnoreCase("stop")){
                    f0.write(source + System.getProperty("line.separator"));
                    
                }
                
                in.close();
            }
            //For appending the content
            else
            {  f0 = new FileWriter(f,true);
                System.out.println("Write 'stop' when you finish appending file ");
                while(!(source=bf.readLine()).equalsIgnoreCase("stop")){
                    f0.append(source+ System.getProperty("line.separator"));
                }
            }
            f0.close();
            
        }
        catch(Exception e){
            System.out.println("Error : " );
            e.printStackTrace();
        }
        
        
    }
    
    
    
}

class FReading {
    public static String str="";
    
    public FReading() {
        
        try{
            File f5=new File("file1.txt");
            if(! f5.exists())
            f5.createNewFile();
            FileReader fl=new FileReader(f5);
            BufferedReader bf=new BufferedReader(fl);
            //For reading till end
            while((str=bf.readLine())!=null){
                System.out.println(str);
            }
            fl.close();
            }catch(Exception e){
            System.out.println("Error : " );
            e.printStackTrace();
        }
    }
}

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry