You are on page 1of 2

PRACTICAL NO 8

File Handling
A)Write a java program to open a file and display the contents in the console
window.
INPUT:
import java.io.*;
class filewrite {
public static void main(String args[]) throws Exception {
byte b[]=new byte[300];
System.out.println("Enter data into the file :-- ");
int c=System.in.read(b);
FileOutputStream fout=new FileOutputStream("omkar.txt");
fout.write(b,0,c);
System.out.println("\nData is written successfully...");
fout.close();
}
}
OUTPUT:
D:\omkar\SEMESTER 4\Core Java\java>java filewrite
Enter data into the file :--
Light is a electromagnetic radiation.what we see as visible light is only a tiny fraction of the
electromagnetic spectrum which extends from very low frequency radio waves through
microwave,infrared,visible & ultraviolet light to x-rays & ultra energic gamma rays.
Data is written successfully...

B) Write a java program to copy the contents from one file to other file.
INPUT:
import java.io.*;
class filecopy {
public static void main(String args[]) throws Exception {
FileInputStream fin=null;
FileOutputStream fout=null;
try {
fin=new FileInputStream("omkar.txt");
fout=new FileOutputStream("omkar.txt");
int c;
while((c=fin.read())!=-1) {
fout.write(c);
}
System.out.println("\nFile copied successfully.");
}
finally {
if(fin!=null) {
fin.close();
}
if(fout!=null)
{
fout.close();
}
}
}
}
OUTPUT:
D:\omkar\SEMESTER 4\Core Java\java>java copyfile
File copied successfully.

C) Write a java program to read the student data from user and store it in the
file.
INPUT:
import java.io.*;
class fileread {
public static void main(String args[]) throws Exception {
int c,check;
FileInputStream fin=new FileInputStream("omkar.txt");
char str[]=new char[300];
check=fin.available();
for(c=0;c<check;c++) {
str[c]=((char)fin.read());
System.out.print(str[c]);
}
fin.close();
}
}
OUTPUT:
D:\omkar\SEMESTER 4\Core Java\java>java fileread
Light is a electromagnetic radiation.what we see as visible light is only a tiny fraction of the
electromagnetic spectrum which extends from very low frequency radio waves through
microwave,infrared,visible & ultraviolet light to x-rays & ultra energic gamma rays.

You might also like