Friday 25 March 2016

Java IO - Part 1



Introduction:  IO has been a part of Java since the very beginning beginning. In Java 1.4 NIO i.e. new input output was added for increasing input/output performance and making it easier to use.

NIO.2 was added to Java SE 7, which uses very powerful I/O techniques which can handle huge data for I/O operations and give a good performance
.

There can be many different types of I/O operations e.g. File I/O, Console I/O, thread I/O, High Performance I/O, Byte Oriented I/O, Character Oriented I/O, I/O Filtering, Wrapping, Serialization.

We will cover Basic File IO in this post. We will use Readers and Writer classes because we will be reading and writing characters. We will read and write bytes with use of Stream classes in the upcoming tutorials. Below are some important classes that we need to know before we begin with hands on practice:



1. File: This class is used for making new empty files, directories, searching for files etc.


2. FileReader:  It is used to read character files. Its read() method method allows you read single character or a fixed bunch of characters. FileReader is a low level class and usually wrapped by higher level classes like BufferedReader.

3. BufferedReader: It is used to improve performance of lower level reader classes like FileReader and make them easier to use. BufferedReader can handle large chunks of data. It makes use of buffering technique where data is stored in buffer and thus increasing performance.

4. FileWriter: Like FileReader, FileWriter is also a lower level class. Its write() methods allows write characters or strings to a file. FileWriters are wrapped by higher level writers like BufferedWriters or PrintWriters

5. BufferedWriter: This class is used to make lower level writer classes like FileWriter efficient and easier for use. Like BufferedReader, they also handle large chunk of data and create a buffer of data.

6. PrintWriter: This class is provides some of powerful methods for formatting data and reading from and writing to files. After Java 5 changes, you can build PrintWriters with files and string as well. There are some new methods like format(), printf() and append() making it very flexible.

7. Console: Added in java 6, this class provides methods to read input from the console and write output to console (which can also be formatted by this class).


Creating Files Using the File Class:


The java File class object represents an actual file or directory on your machine. IO operations are risky and involve checked exceptions to so will put IO related code inside try block and catch IOException. Let's create a file:



package com.bpjoshi.javapriest.iotutorials;

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

/**
 * @author Bhagwati Prasad (Joshi)
 * */
class WriteAFile {
    public static void main(String[] args) {
        try {
  File file = new File("firstFile.txt");
  // you didn't create a file yet
  // you just created a filename
  System.out.println(file.exists());
  // exists() method of file class
  // The code above will print false
  file.createNewFile();
  // createNewFile() method to create file
  System.out.println(file.exists());
  // This will now print true
 } catch (IOException ex) {
  System.out.println(ex);
 }
    }
}





FileWriter and FileReader:  Using FileWriter to write to a file and FileReader to read from the file.(Note: FileReaders and FileWriters are used with  Buffered Readers and Writers mostly)



package com.bpjoshi.javapriest.iotutorials;

import java.io.File;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.IOException;

/**
 * @author Bhagwati Prasad (Joshi)
 * */
class ReaderWriterFile {
    public static void main(String[] args) {
        try {
  File file = new File("firstFile.txt");
  FileWriter fw = new FileWriter(file);
  // Code above creates a file
  fw.write("Hello World"); // Write Hello World to file
  fw.flush(); // flush the data to file before closing
  fw.close(); // closing the file after writing
  FileReader fr = new FileReader(file); // FileReader object
  char[] chArr = new char[20];
  // character array that stores file content
  fr.read(chArr); // read the whole file & put content in chArr
  for (char ch : chArr) { // looping through file content array
   System.out.print(ch);
  }
  fr.close(); // finally close the reader
 } catch (IOException ex) {
  System.out.println(ex);
 }
    }
}



Explanation:  The program above creates a FileWriter object which is referenced by FileWriter type reference variable fw. At the same time, an empty text file is created in the current directory. We write a string to the file and we flush the data. Flush is used, because some of the data is present in buffers. If you do many write operations and at the end you call flush(), it makes sure the last bits of your data have also been stored in the file. The file is closed at the end of read and write operations, because otherwise program will not free this file resource otherwise.


We would like to use a smarter way of writing to and reading from a file which is able to write and read huge amount of data. We will have to use higher level classes for that purpose. One thing is sure, we will always use File type of object for our file, hence these higher level classes, if accept File as a constructor, it will be really good.

Checkout PrintWriter class, it has a constructor that accepts File object. Looking at it's methods, it provides a number of methods to write to a file. For example methods like print(), println(), write(), flush() and close() etc. 

We can safely write:




package com.bpjoshi.javapriest.iotutorials;

import java.io.File;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * @author Bhagwati Prasad (Joshi)
 * */
class HighLevelFileOperation{ public static void main(String[] args){ try{ File file= new File("myFile.txt"); //Declare a file PrintWriter pw = new PrintWriter(file); //Creates a PrintWriter object and a file in directory pw.println("Hello there!"); pw.println("I am studying IO."); //This writes the data to File pw.flush(); pw.close(); //Flush and close PrintWriter FileReader fr= new FileReader(file); //Load the file using FileReader BufferedReader br = new BufferedReader(fr); //Create a high level Reader, i.e. BufferedReader String line= br.readLine(); //Read first line from the file System.out.println(line); //It will print first line of the file(i.e. Hello there! br.close();//close the BufferedReader } catch(IOException ex){ System.out.println(ex); } } }



Explaination: BufferedReader accepts FileReader object in its constructor which accepts a File ojbect in its constructor. Low level operation objects are chained inside High level operation objects.


Playing in deep with Files and Directories:

1. File class is use to create file, delete file, rename file, check whether file exists, create directory etc.
2. File file= new File("myFile.txt") It doesn't create any file, but if a file with name myFile.txt already exists a reference to that existing file is returned.

3.  To create an actual file on disk, either call file.createNewFile() or make a                 PrintWriter/BufferedWriter Object.

4. Creating a Directory using File class: 

File myDir= new File("myDir");
myDir.mkdir();

5. You can create file in the newly create directory myDir:

File file= new File(myDir, "myFile.txt");
myFile.createNewFile();

6. Now you can write to this file in myDir directory using PrintWriter:
PrintWriter pw = new PrintWriter(file);
pw.println("Hello Java World");
pw.flush();
pw.close();

7. You have to make directory yourself, there is no way, PrintWriter or other high level Writer classes will create directory for you unlike file which is can be created by these. Be Aware! This will generate java.io.IOException: No such file or directory

8. Your file object can have reference to an existing directory. Now how to check, if it's a directory: boolean b=myDir.isDirectory()

Let's apply the skills learnt so far to create the program below: FileAndDirectory.java




package com.bpjoshi.javapriest.iotutorials;

import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Bhagwati Prasad (Joshi)
 * */
public class FileAndDirectory {
 public static void main(String[] args) {
  try {
   // Make a directory on path H:\Tutorials
   File ioDir = new File("H:\\Tutorials\\IODirectory");
   ioDir.mkdir();
   // Add a file to directory
   File file = new File(ioDir, "myProfile.txt");
   // Create an actual file on the directory
   file.createNewFile();
   
   //Add content to the File using PrintWriter
   PrintWriter pw= new PrintWriter(file);
   pw.println("I am a java tutor.");
   pw.println("I am a java developer as well.");
   pw.flush();
   pw.close();
   
   //Read from the  File
   FileReader fr= new FileReader(file);
   BufferedReader br= new BufferedReader(fr);
   String str;
   while(((str=br.readLine())!=null)){
    System.out.println(str);
   }
   //When there is no more data, br.readLine() returns null
   br.close();   //Close the BufferedReader
   
   //Create and Delete Another File in the directory
   File file1=new File(ioDir, "yourProfile.txt");
   file1.createNewFile();
   file1.delete(); //This will delete the newly created file
   
   //To rename this file create a new File reference
   File newFile= new File(ioDir, "abcd.txt");
   file.renameTo(newFile); //Wil change name to abcd.txt
   
   //Search files in the directory
   //Let's create a directory H:\Tutorials\IODirectory\IOSearch
   //Create 4-5 Text files in the directory to be searched
   //String array files will hold names of Files
   String[] files= new String[100];
   //Directory
   File search=new File("H:\\Tutorials\\IODirectory\\IOSearch");
   //List  all files in directory
   files=search.list();
   //Printing names from directory
   for(String fileName: files){
    System.out.println("Files found "+fileName);
   }
  } catch (IOException ex) {
   ex.printStackTrace();
  }
 }

}



Java.io.Console class is used for reading input and showing output to console elements i.e. keyboad and monitor screen. It has two important methods, a) readLine() which reads in form of string and b) readPassword() method which returns an character array.

Passwords are stored in character array because once you are done with the array object you can nullify it while string will be present somewhere in the string constant pool, which is a security risk.

That's it for this tutorial, in case of any queries or suggestions, feel free to comment.

Happy Coding!

No comments:

Post a Comment

Please write your views