Expt08 169

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

: B4

Roll No:169
Experiment No: 8
Title: Simple file handling program in java.
Problem Statement:
Take file name as input to your program through command line, If file is existing the open
and display contents of the file. After displaying contents of file ask user – 1.do you want to
add the data at the end of file or 2.replace specified text in file by other text. Based on
user’s response, then accept data from user and append it to file. If file in not existing then
create a fresh new file and store user data into it. Also. User should type exit on new line to
stop the program. Do this program using Character stream classes.

Program:
import java.util.*;
import java.io.*;
class Expt8{
public static void main(String [] args){
Scanner sc=new Scanner(System.in);
try{
System.out.println("Enter your file name :");
String fn=sc.next();
File f1=new File(fn);
if(f1.isFile())
{
System.out.println("File exist");
int ch;
do{
System.out.println("Enter your choice :");
System.out.println("1.read_existing file()\n 2.append data()\n
3.replace data()\n 4.exit()\n");
ch=sc.nextInt();
switch(ch){
case 1 :
FileReader fr=new FileReader(fn);
BufferedReader b=new BufferedReader(fr);
String l;
while((l=b.readLine())!=null)
{
System.out.println(l);

}
break;
case 2 :
PrintWriter pw=new PrintWriter(new BufferedWriter
(new FileWriter(fn,true)));
String str;
System.out.println("Enter the data to append into file :");
while(!(str=sc.nextLine()).equals("exit"));
{
pw.write(str+"\n");
}
break;
case 3:
BufferedReader br=new BufferedReader(new
FileReader(fn));
String rline,line,replaceline;
String originalcontent="";
String newcontent;
System.out.println("Enter the data to be replace into
file :");
rline=sc.nextLine();
System.out.println("Enter the replaced data :");
replaceline=sc.nextLine();
while((line=br.readLine())!=null)
{
originalcontent+=line+System.lineSeparator()
}
newcontent=originalcontent.replace(rline,replaceline);
BufferedWriter bw=new BufferedWriter(new FileWriter(fn));
bw.write(newcontent);
br.close();
bw.close();
break;
case 4:
return;
default:
System.out.println("WRONG CHOICE");
}
}while(ch!=4);
}else
{
System.out.println("File not found \nCreat new file "+fn);
}
}catch(Exception e)
{
System.out.println(e);
}
}
}

Output:

You might also like