Recent Posts

Wednesday, 10 August 2016

File I/O & Serialization Tutorial


File I/O Introduction
     The following is the list methods going to cover in File I/O Concept.
1. File
2. FileWriter
3. FileReader
4. BufferedWriter
5. BufferedReader
6. printWriter

1. File
     A java file object represent just name of the file/directory.
File file = new File(ashok.txt”);
     If ashok.txt’ is already available then ‘file’ will represent that physical file.
E.g
package com.ashok.files;

import java.io.File;
import java.io.IOException;

public class MyFile {
   public static void main(String[] args) {
      File f = new File("ashok.txt");
      System.out.println(f.exists());
      try {
         f.createNewFile();
      } catch (IOException e) {
         e.printStackTrace();
      }
      System.out.println(f.exists());
   }
}
Output
1st Run
false
true

2nd Run
true
true
     A java file Object can represent directories also
E.g
package com.ashok.files;

import java.io.File;
import java.io.IOException;

public class MyFile {
   public static void main(String[] args) {
      File f = new File("ashok");
      System.out.println(f.exists());
      f.mkdir();
      System.out.println(f.exists());
   }
}
Output
1st Run
false
true

2nd Run
true
true
The constructors of the file class
1. File f = new File(String name)
     Here name may be file or directory name. Creates a java file object that represents a file or directory name.

2. File f = new File(String subdirec, String name)
     Creates a java file object that represents file or directory name present in specified subdirectory.

3. File f = new File(File subdir, String name)

Important methods of File Class
1. boolean exists()
     Returns true if the physical file/directory presents other wise false.

2. boolean createNewFile()
    Returns ture if it creates a new file, if the required file is already available then it won’t create any new file and returns false.

3. booelan mkdir()
     For creation of directory.

4. boolean isFile()
     Returns true if the java file object represents a file.

5. boolean isDirectory()
     Returns true if the java file object represents a directory.

6. String [] list()
     Returns the names of files and directories present in the directories represented by the file object. If the java file object represents a file instead of directory this method returns null.

7. Boolean delete()
     For deleting the file or directory represented by java file object.
Write code to create a file named with ashok.txt in current working directory.
import java.io.File;
import java.io.IOException;
class MyFile {
   public static void main(String[] args)throws IOException {
      File f = new File("demo.txt");
      f.createNewFile();
   }
}
Write code to create a directory named with Waytoeasylearn in current working directory and create a file named with ashok.txt in that directory.
import java.io.File;
import java.io.IOException;
class MyFile {
   public static void main(String[] args)throws IOException {
      File f1 = new File("Waytoeasylearn");
      f1.mkdir();
      File f2 = new File("Waytoeasylearn","ashok.txt");
      f2.createNewFile();
   }
}
Write code to create a file named with ashok.txt present in c:\\Waytoeasylearn folder.
import java.io.File;
import java.io.IOException;
class MyFile {
   public static void main(String[] args)throws IOException {
      File f = new File("c:\\Waytoeasylearn","ashok.txt");
      f.createNewFile();
   }
}
2. FileWriter
     This class can be used for writing character data to the file.
Constructors
1. FileWriter fw = new FileWriter(String fname)
2. FileWriter fw = new FileWriter(File f);

     The above 2 constructors creates a file object to write character data to the file. If the file already contains some data it will overwrite with the new data. Instead of overriding if u have to perform append then we have to use the following constructors.

FileWriter fw = new FileWriter(String name, boolean append);
FileWriter fw = new FileWriter(File f, boolean append);

     If the underlying physical file is not already available then the above constructors will create the required file also.

Important methods of FileWriter Class
1. void write(int ch) throws IOException
     For writing single character to the file.

2. void write(String s)throws IOException.

3. void write(char [] ch) throws IOException.

4. void flush()
     To guaranteed that the last character of the data should be required to the file.
E.g
package com.ashok.files;

import java.io.File;
import java.io.FileWriter;

public class MyFile {
   public static void main(String arg[]) throws Exception {
      File f = new File("Ashok.txt");
      System.out.println(f.exists());
      FileWriter fw = new FileWriter(f, true);
      System.out.println(f.exists());
      fw.write(97);
      fw.write("Hai\nHow are you\n");
      char[] ch1 = { 'a', 'b', 'c' };
      fw.write(ch1);
      fw.flush();
      fw.close();
   }
}
Output
true
true

In Ashok.txt 
1st time
aHai
How are you
abc

2ndtime
aHai
How are you
abcaHai
How are you
abc
3. FileReader
     This class can be used for reading character data from the file.
Constructors
1. FileReader fr = new FileReader(String name);
2. FileReader fr = new FileReader(File f);

Important methods of FileReader Class
1. int read():
     For reading next character from the file. If there is no next character this method returns -1

2. int read(char[] ch):
     To read data from the file into char array.

3. void close():
     To close FileReader
E.g
package com.ashok.files;

import java.io.File;
import java.io.FileReader;

public class MyFile {
   public static void main(String arg[]) throws Exception {
      File f = new File("Ashok.txt");
      FileReader fr = new FileReader(f);
      System.out.println(fr.read());
      char[] ch2 = new char[(int) (f.length())];
      System.out.println(ch2.length);
      fr.read(ch2);
      for (char ch1 : ch2) {
         System.out.print(ch1);
      }
   }
}
Output
97
40
Hai
How are you
abcaHai
How are you
abc
     The usage of FileReader and FileWriter is in efficient because
* While writing the data by using FileWriter, program is responsible to insert line separators manually.

* We can read the data character by character only by using FileReader. If increases the number of I/O operations and effect performance.
    To overcome these problems sun people has introduced BufferedReader and BufferedWriter classes.
4. BufferedWriter
     This can be used for writing character data to the file.

Constructors
1. BufferedWriter bw = new BufferedWriter(writer w)
2. BufferedWriter bw = new BufferedWriter(writer r, int size)

     BufferedWriter never communicates directly with the file. It should Communicate through some writer object only.
1. BufferedWriter bw = new BufferedWriter(“ashok.txt”); // Invalid
2. BufferedWriter bw = new BufferedWriter(new File(“ashok.txt”)); // Invalid
3. BufferedWriter bw = new BufferedWriter(new FileWriter(“ashok.txt”)); // Valid
4. BufferedWriter bw = new BufferedWriter(new BufferedWriter(new FileWriter(“ashok.txt”))); // Valid

Important methods of BufferedWriter Class
1. void write(int ch) thorows IOException
2. void write(String s) throws IOException
3. void write(char[] ch) throws IOException
4. void newLine()
     For inserting a new line character.
5. void flush()
6. void close()
E.g
package com.ashok.files;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

public class MyFile {
   public static void main(String arg[]) throws Exception {
      File f = new File("ashok.txt");
      System.out.println(f.exists());
      FileWriter fw = new FileWriter(f);
      BufferedWriter bw = new BufferedWriter(fw);
      bw.write(97);
      bw.newLine();
      char [] ch = {'a','b','c','d'};
      bw.write(ch);
      bw.newLine();
      bw.write("Ashok");
      bw.newLine();
      bw.write("Waytoeasylearn");
      bw.flush();
      bw.close();
   }
}
Output
true

In ashok.txt
a
abcd
Ashok
Waytoeasylearn
Note
     When ever we r closing BufferedWriter ,automatically underlying FileWriter object will be closed.

5. BufferedReader
     By using this class we can read character data from the file.

Constructors
1. BufferedReader br = new BufferedReader(Reader r)
2. BufferedReader br = new BufferedReader(Reader r, int buffersize)
     BufferedReader never communicates directly with the file. It should Communicate through some reader object only.

Important methods of BufferedReader Class
1. int read()
2. int read(char [] ch)
3. String readLine();
     Reads the next line present in the file. If there is no nextline this method returns null.
4. void close()
E.g
package com.ashok.files;

import java.io.BufferedReader;
import java.io.FileReader;

public class MyFile {
   public static void main(String arg[]) throws Exception {
      FileReader fr = new FileReader("ashok.txt");
      BufferedReader br = new BufferedReader(fr);
      String s = br.readLine();
      while (s != null) {
         System.out.println(s);
         s = br.readLine();
      }
      br.close();
   }
}
Output
a
abcd
Ashok
Waytoeasylearn
Note
     When ever we r closing BufferedReader ,automatically underlying FileReader object will be closed.

6. PrintWriter
* PrintWriter is the most enhanced Writer to write text data to the file.

* By using FileWriter and BufferedWriter we can write only character data to the File but by using PrintWriter we can write any type of data to the File.

Constructors
1. PrintWriter pw = new PrintWriter(String fname)
2. PrintWriter pw = new PrintWriter(File f);
3. PrintWriter pw = new PrintWriter(Writer w);

Note
     PrintWriter can communicate either directly to the File or via some Writer object also.

Important methods
1. write(int ch)
2. write(char [] ch)
3. write(String s)
4. print(int i)
   print(double d)
   print(char ch)
   print(Boolean b)
   print(char ch[])
5. void flush()
6. close()
E.g
package com.ashok.files;

import java.io.FileWriter;
import java.io.PrintWriter;

public class MyFile {
   public static void main(String arg[]) throws Exception {
      FileWriter fw = new FileWriter("ashok.txt");
      PrintWriter out = new PrintWriter(fw);
      out.write(97);
      out.println(100);
      out.println(true);
      out.println('c');
      out.println("Waytoeasylearn");
      out.flush();
      out.close();
   }
}
Output
In ashok.txt file
a100
true
c
Waytoeasylearn

Next Tutorial  File I/O & Serialization Tutorial Part 2 

No comments:

Post a Comment