File Handling in Java





  • Java provides a number of classes and methods that allow you to read and write files.

  • In Java, all files are byte-oriented, and Java provides methods to read and write bytes from and to a file.

  • Two of the most often-used stream classes are FileInputStream and FileOutputStream

  • To open a file, we simply creates an object of one of these classes, specifying the name of the file as an argument to the constructor.

  • While both classes support additional, overridden constructors:

  • FileInputStream Constructors :

  • FileInputStream ( String fileName ) throws FileNotFoundException

  • FileInputStream ( File file ) throws FileNotFoundException

  • OutputStream Constructors :

  • FileOutputStream(String fileName) throws FileNotFoundException

  • FileOutputStream(String filename, boolean mode) throws FileNotFoundException

  • FileOutputStream(File file) throws FileNotFoundException

  • FileOutputStream(File file, boolean mode) throws FileNotFoundException

  • The constructor with boolean ( true ) parameter opens file for writing in append mode.


Code to Read File :

import java.io.FileInputStream;
class FileReadDemo
{
 public static void main(String[] ar)
 {
  FileInputStream fis = null;
  try{
  fis = new FileInputStream("data.txt");
  int ch;
  while(true)
   {
    ch = fis.read();
    if(ch==-1)
     {
      break;
     }
    System.out.println(ch);
   }
  }
 catch(Exception e)
  {
   System.out.println(e);
  }
 }
}           

Code to Write on File :

import java.io.FileOutputStream;
class FileReadDemo
{
 public static void main(String[] ar)
 {
  FileOutputStream fos = null;
  try{
  fos = new FileOutputStream("data.txt");
  String data = "Java Prowess";
   for(int i=0; i< data.length();i++)
   {
     fos.write(data.charAt(i));
   }
  }
 catch(Exception e)
  {
   System.out.println(e);
  }
 }
}           

Next topic is wrapper-classes




 

Training For College Campus

We offers college campus training for all streams like CS, IT, ECE, Mechanical, Civil etc. on different technologies like
C, C++, Data Structure, Core Java, Advance Java, Struts Framework, Hibernate, Python, Android, Big-Data, Ebedded & Robotics etc.

Please mail your requirement at info@prowessapps.in


Projects For Students

Students can contact us for their projects on different technologies Core Java, Advance Java, Android etc.

Students can mail requirement at info@prowessapps.in



CONTACT DETAILS

info@prowessapps.in
(8AM to 10PM):

+91-9026070669 , +91-9451396824

© 2016, prowessapps.in, All rights reserved