File Handling
File Handling
Recursion Iteration
1. Function calls itself. 1. A set of instructions repeatedly
2. Size of code is smaller than executed.
iteration. 2. Size of code is larger than
3. It takes more time for recursion.
execution 3. It takes less time for execution
File handling
File Operations:
1. File Input(Reading from file)
2. File Output(Writing to the file)
Types of File:
1. Text or Character File
2. Binary File
Binary Files:
1. To write on text file(File Output) - FileOutputStream Class
2. To read from text file(File Input) - FileInputStream Class
import java.io.*;
import java.util.Scanner;
class textout
{
public static void main(String arg[])throws IOException
{
Scanner sc=new Scanner(System.in);
FileWriter fw=new FileWriter("Students.txt");
BufferedWriter bw=new BufferedWriter(fw);
PrintWriter pout=new PrintWriter(bw);
for(int i=1;i<=5;i++)
{
System.out.println("Enter name");
String name =sc.nextLine();
pout.println(name);
}
pout.close();
}
}
import java.io.*;
class textin
{
public static void main(String arg[])throws IOException
File Handling Page 3
public static void main(String arg[])throws IOException
{
FileReader fr=new FileReader("Students.txt");
BufferedReader br= new BufferedReader(fr);
String name;
while((name=br.readLine())!=null)
{
System.out.println(name);
}
br.close();
}
}
import java.io.*;
import java.util.Scanner;
class binout
{
public static void main(String arg[])throws IOException
{
Scanner sc=new Scanner(System.in);
int rno;
double marks;
FileOutputStream fout=new FileOutputStream("Marks.dat");
DataOutputStream dout=new DataOutputStream(fout);
for(int i=1;i<=5;i++)
{
System.out.println("Enter roll number");
rno=sc.nextInt();
System.out.println("Enter marks");
marks=sc.nextDouble();
File Handling Page 4
marks=sc.nextDouble();
dout.writeInt(rno);
dout.writeDouble(marks);
}
dout.close();
fout.close();
}
}
Ans:
void findProduct(int p)
{
Scanner sc=new Scanner(System.in);
FileInputStream fr=new FileInputStream("Invoice.dat");
DataInputStream dr=new DataInputStream(fr);
boolean eof=false;
int f=0;
while(!eof)
{
try
{
int pc;
double up;
int q;
pc=dr.readInt();
up=dr.readDouble();
q=dr.readInt();
File Handling Page 6
q=dr.readInt();
if(p==pc && q>0)
{
System.out.println("Available quantity product="+q);
f=1;
break;
}
catch(EOFException e1)
{
System.out.println("end of file");
eof=true;
}
}
if(f==0)
System.out.println("Item is not available");
}