Write a java program to accept filename and display it's content (byte by byte) using FileInputStream class.

 import java.io.*;  //importing module for file and FileInputStream Class
import java.util.*;
class MyFile
{
File f;   //declaring file object
MyFile()
{
Scanner s= new Scanner(System.in);
System.out.println("Enter the path of file: ");  //accepting file path
String path=s.next();
System.out.println("Enter the name of file: ");  //accepting file name
String name=s.next();
f=new File(path,name);  //initializing file object
}
void display()   //creating a method to display content of file
{
try
{
if (f.exists() && f.isFile())  // checking whether entered file name exists and whether it is file or not...
{
FileInputStream fin = new FileInputStream(f);    //creating the FileInputStream object in order to read the content of file
System.out.println("Content of File: ");
while(true)
{
int i=fin.read();
if (i==-1)      // When file pointer reaches to the end of the file read function returns -1 
break;
System.out.print((char)i);  //TypeCasting-read function returns the content of file in int format (i.e. ASCII) so we need to convert it into char
}
}
}catch(Exception e)   //FileInputStream class object throws exceptions so we need to catch those exceptions using try and catch block
{
System.out.println(e);
}
}
}
class TestMyFile
{
public static void main(String args[])
{
MyFile obj= new MyFile();  //cretating the object of our class which is defined above and it will automatically call the constructor
obj.display();  // calling the display method 
}
}

0 Comments