Java Program on How to Read Data from File

Free Java courses with 37 real-time projects - Learn Java

Program 1

package dataflair;
import java.io.*;
public class TestRead1 
{
    public static void main(String[] args) throws IOException
    {
       File F=new File("d://dataflair/student.txt");
       char ch;
       int n;
       if(F.isFile())
       {
       FileInputStream fis=null;
       
       try
       {
           fis=new FileInputStream(F);
           while((n=fis.read())!=-1)
           {
               ch=(char)(n);
               System.out.print(ch);
           }   
       }
       
       finally
       {
          fis.close();
       }
     }   
     else
            System.out.println("File not Found......");   
    }
    
}

Program 2

package dataflair;
import java.io.*;
public class TestRead2 
{
    public static void main(String[] args) throws IOException
    {
       File F=new File("d://dataflair/student.txt");
       char ch;
     
       if(F.isFile())
       {
          FileInputStream fis=null;
       
         try
         {
           fis=new FileInputStream(F);
           int n;
           n=(int)(F.length());
           byte b[];
           b=new byte[n];
           fis.read(b);
           String S=new String(b);
           System.out.println(S);
         }
         finally
        {
          fis.close();
        }
     }   
    }
    
}

 

You give me 15 seconds I promise you best tutorials
Please share your happy experience on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *