IO Class

What is IO class ?


You know that Java provides so many predefined classes to make your code easily. IO class is another special class that helps you to create files and modify them. There are special sub classes within IO class to do these things. In this post I want to talk about following classes. Because they are the main classes that you want to learn for OCPJP 1Z0-851 examination.

  • File
  • FileWriter
  • BufferedWriter
  • FileReader
  • BufferedReader
  • PrintWriter
  • Console

In OCPJP 1Z0-851 examination, we have to consider only about above things. In additionally I have noted down few things over the syllabus. Keep these thing in your mind and try to do examples to improve your knowledge with them. 
   

File class


File class in an abstract representation of file and directory path names. This is not used to write or read data. It gives you information about files. This class is used for making new empty files, searching files, deleting files, making directories and working with paths

Try this example. This is a sample example for checking a file in a known directory.

  • For example I have created a folder in C directory and created a txt file within it called "myFile.txt". You can create either .txt, .php, .html or whatever file you like. In this demonstration I use .txt file.
  • Then try this code and check your result. If you create that file correctly, you will be able to get "Your file is there" message.

import java.io.*;
public class FileTest {
 public static void main(String args[]){
  File f = new File("C:\\Test\\myFile.txt");
  
  if(f.exists()){
   System.out.println("Your file is there");
  }
  else{
   System.out.println("Your file is not there");
  }
 }
}



  • In this example I have imported java.io class. 
  • It is necessary to add it. Because File class is a sub class of IO class. So you have import IO class manually. 
  • Then in line four, I have created File object, its reference variable is "f".
  • In this line you can see I have used "\\" to set path instead of using "\". This is necessary in windows.
  • Next line I checked existence, using exist( ) function.
  • This is very simple example shows you the importance of File class.


How to create a file ?


Now we know about file class. Before we go to other things I thought to show you how to create files in Java. There are many ways to do it.

Using createNewFile( ) function



import java.io.*;
public class CreateFile {
 public static void main(String args[]){
  
  try{
   File f = new File("C:\\Test\\file1.txt");
   System.out.println(f.exists());
   
   f.createNewFile();
   System.out.println(f.exists());
  }
  catch(Exception e){
   System.out.println("There is an error.");
  }
 }
}



  • In this example also, first I have created file object and gave the path of this file.
  • Then I have used createNewFile( ) function to create a new file in that given destination.
  • At the very first time you will be able to see the output as false and then true. If you run it again it will give true and true as a output. 
  • You can understand what is the reason for that. Very first time there is no file in that destination. But second time there is a file in that destination.

This createNewFile( ) method is Boolean type method. Using this method you cannot create files in same file name. In above example it creates file1.txt file, if it does not already exist. You can run it again and again, but it will not create more file1.txt files, just only one.

Using formatter( ) method



import java.util.*;

public class CreateFile2 {
 public static void main(String args[]){
  
  try{
   new Formatter("C:\\Test\\FormatterFile.txt");
   
   System.out.println("You have created a file");
  }
  catch(Exception e){
   System.out.println("There is an error.");
  }
 }
}


  • This is another method of creating files.
  • In this method we use Formatter( ) class to create files.
  • Special thing is there, you can see I have not imported IO package, instead of that I have imported util package. Because Formatter class belongs to java.util package.
  • This method is not thread safe for multithreaded access. You need not to worry about this method in your examination and pay your attention for the first method to create files. In later sessions we discuss about Threads. 

Using FileWriter( ) method



import java.io.*;
public class CreateFile3 {
 public static void main(String args[]){
  
  try{
   File f = new File("C:\\Test\\Create File 3.txt");
   new FileWriter(f).close();
  }catch(Exception e){
   System.out.println("There is an error");
  }
 }
}



  • FileWriter( ) method is generally used for writing characters. 
  • But this method also create files.
  • In this program I have used close( ) method. This is used to prevent resource leak. You can run it without using close( ) method. But It is good practice to use close( ) to prevent resource leak. You may learn more about close( ) in later.


How to write in a file ?


Now we know how to create files. Then lets try to write something on the file that we have created. There are also few methods to do it.

Using write( ) method


import java.io.*;
public class WriteFile {
 public static void main(String args[]){
  
  try{
   File f = new File("C:\\Test\\write.txt");
   FileWriter fw = new FileWriter(f);
   
   fw.write("This is a test");
   fw.close();
   
  }catch(Exception e){
   System.out.println("There is an error");
  }
 }
}



  • This is also like previous examples.
  • write( ) method allows you to write characters and string in to your file.
  • close ( ) method is used to prevent resource leak and stop writing to the file. If you try to write something after close( ) method, it will not printed to the file( write.txt ) and there can be an run-time exception. In this program you will be able to see a message "There is an error".  

Using format( ) method


import java.util.*;

public class WriteFile2 {
 public static void main(String args[]){
  
  try{
   
   Formatter f = new Formatter("C:\\Test\\WriteFile2.txt");
   f.format("%s%s", "Ravi ", "easyjavase@live.com ");
   f.close();
   
  }catch(Exception e){
   System.out.println("There is an error");
  }
 }
}


  • You know how to create file using Formatter( ) class.
  • Then what I did is, using format( ) method to write something to a file you have created.


How to read a file ?


Already you know how to create files and how to write in to the files. Then we have to discuss how to read a file.

Using FileReader( ) method


  • This is a very simple method that can be used to read a file.
  • Following example shows the way, that how can you do it.
  • As a Java programmer we should have to familiar with other operating systems also, specially Ubuntu.
  • In this program I code this program in Ubuntu OS. So I have to use path in different way. In Ubuntu it is easy to fine the path. Just you have to drag and drop the file to the ubuntu terminal. Then you will able to see the path and then you can copy it and paste it in your program.
  • If you are using Windows You can use the path as we used before (C:\\Test\\ReadFile.txt). 



import java.io.*;
public class FileReaderTest {
 public static void main(String args[]){
  
  try{
   /*this program is created in ubuntu. If you are with windows, 
     you have to change the file path as above programs.*/

   File f = new File("/home/ravi/workspaceUbuntu/IOTest/src/Reader.txt");
   FileReader fr = new FileReader(f);
   
   char a[] = new char[50];
   fr.read(a);
   
   for(char c: a){
    System.out.print(c);
   }
   fr.close();
   
  }catch(Exception e){
   System.out.println("There is an error");
  }
 }

}



I think post was too long, I hadn't any idea about termination point. In next post I am going to talk about BufferWriter, BufferReader, PrintWriter and differences between FileWriter, FileReader and so on. Hope you enjoy...!!!




IO Class IO Class Reviewed by Ravi Yasas on 9:49 PM Rating: 5

No comments:

Powered by Blogger.