File Handling in Java::Reading and Writing

Reading and writing files in Java using Formatter, Scanner and bufferedreader:


Simple Open a File in Java:

package myfirstproject;
import java.io.*;
public class MyFirstProject {  
    public static void main(String args[]) throws IOException
   {
      File name=new File("C:\\usman\\input.txt");
      if(name.exists()){
          System.out.println(name.getName()+"File is exists");
      }
      else{
          System.out.println("File does not exists");
      }
}
}


Craete New File in Java:

package myfirstproject;
import java.io.*;
import java.util.*;

public class MyFirstProject {  
    public static void main(String args[]) throws IOException
   {
       /*final Formatter x;
       x =new  Formatter("C:\\usman\\fatima.txt");
     
     
*/      File name=new File("C:\\usman\\input1.txt");
        name.createNewFile();
      if(name.exists()){
          System.out.println(name.getName()+"File is exists");
      }
      else{
          System.out.println("File does not exists");
      }
}


}Write in File Using Formatter in Java:
package myfirstproject;
import java.io.*;
import java.util.*;
import java.lang.*;

public class MyFirstProject {  
    public static void main(String args[]) throws IOException
   {
       final Formatter x;
       x = new Formatter("C:\\usman\\usman.txt");
       x.format("%s%s%s%d", "usman " ,"Siddique ", "fatima " ,3);
     
       File name=new File("C:\\usman\\usman.txt");
       if(name.exists()){
           System.out.println("true");
      }
     
       x.close();
}

}



Reading File Using Scanner in Java:
package myfirstproject;
import java.io.*;
import java.util.*;
import java.lang.*;

public class MyFirstProject {  
    private Scanner a;
    public static void main(String args[]) throws IOException
   {
       final Formatter x;
       x = new Formatter("C:\\usman\\input.txt");
     
        MyFirstProject obj=new MyFirstProject();
        obj.a=new Scanner(new File("C:\\usman\\usman.txt"));
        while(obj.a.hasNext()){
            String value=obj.a.next();
       x.format("\n%s\t%d", value  ,3);
        }
       File name=new File("C:\\usman\\usman.txt");
       if(name.exists()){
           System.out.println("true");
      }
     
       x.close();
}

}





Read File using BufferedReader:
package myfirstproject;
import java.io.*;
import java.util.*;
import java.lang.*;


public class MyFirstProject {  
    private Scanner a;
    public static void main(String args[]) throws IOException
   {
       BufferedReader br =null;
       String line=null;
       br= new BufferedReader(new FileReader("C:\\usman\\usman.txt"));
       while((line=br.readLine())!=null){
           System.out.println(line);
       }
       br.close();
     
}

}


No comments

Powered by Blogger.