Monday, 9 May 2016

File Handling

Simple programs using File Handling.


Writing something to a file :
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import java.io.*;  
class Test{  
  public static void main(String args[]){  
   try{  
     FileOutputstream fout=new FileOutputStream("abc.txt");  
     String s="Sachin Tendulkar is my favourite player";  
     byte b[]=s.getBytes();//converting string into byte array  
     fout.write(b);  
     fout.close();  
     System.out.println("success...");  
    }catch(Exception e){system.out.println(e);}  
  }  
}  

Reading from a file :
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import java.io.*;  
class SimpleRead{  
 public static void main(String args[]){  
  try{  
    FileInputStream fin=new FileInputStream("abc.txt");  
    int i=0;  
    while((i=fin.read())!=-1){  
     System.out.println((char)i);  
    }  
    fin.close();  
  }catch(Exception e){system.out.println(e);}  
 }  
}  

No comments:

Post a Comment

Thank you for spending your valuable time!