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){}
} }