BCA

AJAVA LAB

PROGRAM 1 PROGRAM 2 PROGRAM 3 PROGRAM 4 PROGRAM 5 PROGRAM 6

PART B

PROGRAM 7 PROGRAM 8 PROGRAM 9 PROGRAM 10 PROGRAM 11 PROGRAM 12 PROGRAM 13 PROGRAM 14 PROGRAM 15 . . .

 
 

Question : 6. Write a program to check whether a file exists or not.
            a. If exists display the contents of file
             b. If does not exists create the file



 import java.io.*;
  
// Main class
public class Program6 {
 
    // Main driver method
    public static void main(String args[])
    {


        String filename="atest.txt";
       try
       {  
          
            int i;
            FileInputStream fin;
         

            File f = new File(filename);

        if (f.exists())
        {
             
              System.out.println("FILE  Exists");
  
           
            try
                {
                 fin = new FileInputStream(filename);
                }
                catch(FileNotFoundException e)
                {
                    System.out.println("File Not Found");
                     return;
                 }
                   catch(ArrayIndexOutOfBoundsException e)
                    {
                    System.out.println("Usage: ShowFile File");
                    return;
                    }
        do
        {
                i = fin.read();
                if(i != -1)
                 System.out.print((char) i);
        } while(i != -1);
            fin.close();
        }    
  else
         {

        System.out.println("Does not Exists");
        System.out.println("NEW CREATE");

         FileWriter fWriter = new FileWriter(filename);
         fWriter.write("WELCOME TO FILE HANDLING");
 
          fWriter.close();
        }
            // Show if the file does not exists
           
    
        }catch(IOException e){}
} }