Java Programming

Topic No. 10 : About File Handling

About Scanner Class
Source Code of main class
    public static void main(String[] args) {
        
        Scanner sn = new Scanner(System.in);
       System.out.print("Enter Your Name : ");
       String s1 =  sn.nextLine();
       System.out.print("Enter Your Designation : ");
       String s2 =  sn.nextLine();
       System.out.print("Enter Your Basic Pay : ");
       int s3 =  Integer.parseInt(sn.nextLine());
       System.out.print("\nYour Name is "+s1);
       System.out.print("\nYour Designation is "+s2);
       System.out.print("\nYour Basic Pay "+s3);
    }
    
}          
About File Class
Source Code of main class
import java.io.*;


    public static void main(String[] args) {
        
       try 
        {  
            File file = new File("d:\\bscds.txt");  
            if (file.createNewFile()) 
            {  
                System.out.println("New File is created!");  
            } else 
            {  
                System.out.println("File already exists.");  
            }  
           
        } 
        catch (IOException e) 
        {  
            e.printStackTrace();  
        }  
    }
    
}          
About File Streams
Source Code of main class
import java.io.*;


public class Fileio 
{​​​
    public static void main(String[] args) 
    {​​​

        try
        {​​​
            FileOutputStream fos = new FileOutputStream("d:\\abc.txt");
            //fos.write(40);
            //fos.write(50);
            byte[] b = new byte[100];
            b = "Dhaval".getBytes();

            fos.write(b);
            FileInputStream fis = new FileInputStream("d:\\abc.txt");
            while(5==5)
            {​​​
                int n = fis.read();
                if(n==-1)
                {​​​
                 break;
                }​​​
                else
                {​​​
                    System.out.print((char)n);
                }​​​
            }​​​


        }​​​
        catch(Exception e)
        {​​​
        System.out.print(e.getMessage());
        }​​​
    }​​​
}​​​
File Copy Example
Source Code of main class
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Fileio2 {
    public static void main(String[] args) throws IOException 
    {

        FileReader inputStream = null;
        FileWriter outputStream = null;

        try 
        {
            inputStream = new FileReader("d:\\abc.txt");
            outputStream = new FileWriter("d:\\tanishq.txt");

            int c;
            while ((c = inputStream.read()) != -1) {
            outputStream.write(c);
        }
        } 
        finally {
        if (inputStream != null) {
        inputStream.close();
        }
        if (outputStream != null) {
        outputStream.close();
        }
        }
    }
}