Reading and writing to a file in java

Introduction 

 
In this blog we will know how to read and write to a file in java.
  1. /*File reading by using FileInputStream/FileReader*/    
  2. import  java.io.*;    
  3. import java.util.*;    
  4. public class readFile    
  5. {    
  6. public static void main(String arg[])throws Exception    
  7. {    
  8. System.out.print("Provide name of file to read ");    
  9. Scanner sc=new Scanner(System.in);    
  10. String s=sc.next();    
  11. //FileInputStream fis=new  FileInputStream(s);    
  12. FileReader fis=new  FileReader(s);    
  13. int x;    
  14. while((x=fis.read())!=-1)    
  15. System.out.print((char)x);    
  16. }    
  17. }   
 
compile
 
javac readFile.java
java readFile
  1. /*File writing by using FileOutputStream/FileWriter*/    
  2. import  java.io.*;    
  3. import java.util.*;    
  4. public class writeFile    
  5. {    
  6. public static void main(String arg[])throws Exception    
  7. {    
  8. Scanner sc=new Scanner(System.in);    
  9. System.out.print("Provide file name:");    
  10. String fname=sc.next();    
  11. System.out.print("Provide data to be written:");    
  12. String data=sc.next();    
  13. //To use FileWriter    
  14.  FileWriter fw=new FileWriter(fname,true);    
  15.  fw.write(data);    
  16.  fw.close();    
  17. }    
  18. }    
 
compile
 
javac writeFile.java
java writeFile 
Next Recommended Reading Copy one file to another in java