Are You Feeling any difficulity while writing Core-Java Programs. Send those to me Here.

I/O Packages

I/O Packages

Unit Structure

8.1 Introduction
8.2 Stream
8.2.1 Byte Streams
8.2.1.1 InputStream
8.2.1.2 OutputStream
8.2.2 Character Streams
8.2.2.1 Reader
8.2.2.2 Writer
8.3 How Files and Streams Work
8.4 Classes
8.5 Exceptions Classes
8.6 Standard Streams
8.7 Working with Reader classes
8.7.1 InputStreamReader
8.7.2 BufferedReader
8.8 I/O Streams
8.8.1 FileInputstream
8.8.2 FileOutputStream
8.8.3 DataInputStream
8.9 Finding a File
8.10 Summary

8.1 Introduction

Stream is an abstract demonstration of input or output device. By using stream, we can write or read data. To bring in information, a program is open a stream on an information source (a file, memory, a socket) and read information sequentially. In this unit, we will learn the concept of stream, I/O package.

8.2 Stream:

The Java Input/Output (I/O) is a part of java.io package. The java.io package contains a relatively large number of classes that support input and output operations. The classes in the package are primarily abstract classes and stream-oriented that define methods and subclasses which allow bytes to be read from and written to files or other input and output sources.
For reading the stream:
Open the stream
Read information
Close the stream
For writing in stream:
Open the stream
Write information
Close the stream
There are two types of stream as follows:
o Byte stream
o Character stream

8.2.2 Byte Streams:

It supports 8-bit input and output operations. There are two classes of byte stream
o InputStream
o OutputStream

8.2.2.1 InputStream:

The InputStream class is used for reading the data such as a byte and array of bytes from an input source. An input source can be a file, a string, or memory that may contain the data. It is an abstract class that defines the programming interface for all input streams that are inherited from it. An input stream is automatically opened when you create it. You can explicitly close a stream with the close( ) method, or let it be closed implicitly when the object is found as a garbage.
The subclasses inherited from the InputStream class can be seen in a hierarchy manner shown below:
InputStream
- ByteArrayInputStream
- FileInputStream
- ObjectInputStream
- FilterInputStream
- PipedInputStream
- StringBufferInputStream
- FilterInputStream
o BufferedInputStream
o DataInputStream
o LineNumberInputStream
o PushbackInputStream

8.2.1.2 OutputStream:

The OutputStream class is a sibling to InputStream that is used for writing byte and array of bytes to an output source. Similar to input sources, an output source can be anything such as a file, a string, or memory containing the data. Like an input stream, an output stream is automatically opened when you create it. You can explicitly close an output stream with the close( ) method, or let it be closed implicitly when the object is garbage collected.
The classes inherited from the OutputStream class can be seen in a hierarchy structure shown below:
OutputStream
- ByteArrayOutputStream
- FileOutputStream
- ObjectOutputStream
- FilterInputStream
- PipedOutputStream
- StringBufferInputStream
- FilterOutputStream
o BufferedOutputStream
o DataOutputStream
o PrintStream
OutputStream is also inherited from the Object class. Each class of the OutputStream provided by the java.io package is intended for a different purpose.

8.2.2 Character Streams:

It supports 16-bit Unicode character input and output. There are two classes of character stream as follows:
o Reader
o Writer
These classes allow internationalization of Java I/O and also allow text to be stored using international character encoding.

8.2.2.1 Reader:

- BufferedReader
o LineNumberReader
- CharAraayReader
- PipedReader
- StringReader
- FilterReader
o PushbackReader
- InputStreamReader
o FileReader

8.2.2.2 Writer:

- BufferedWriter
- CharAraayWriter
- FileWriter
- PipedWriter
- PrintWriter
- String Writer
- OutputStreamWriter
o FileWriter

8.3 How Files and Streams Work:

Java uses streams to handle I/O operations through which the data is flowed from one location to another. For example, an InputStream can flow the data from a disk file to the internal memory and an OutputStream can flow the data from the internal memory to a disk file. The disk-file may be a text file or a binary file. When we work with a text file, we use a character stream where one character is treated as per byte on disk. When we work with a binary file, we use a binary stream.
The working process of the I/O streams can be shown in the given diagram.


8.7 Classes:

The following lists of classes are provided by the java.io package shown in the table:


8.5 Exceptions Classes:

The following summary of the exception classes provided by the java.io package shown in the table:


8.6 Standard Streams: 

Standard Streams are a feature provided by many operating systems. By default, they read input from the keyboard and write output to the display. They also support I/O operations on files.


  • Standard Input: - Accessed through System.in which is used to read input from the keyboard.
  •  Standard Output: - Accessed through System.out which is used to write output to be display.
  • Standard Error: - Accessed through System.err which is used to write error output to be display.

Java also supports three Standard Streams:


These objects are defined automatically and do not need to be opened explicitly.


Standard Output and Standard Error, both are to write output; having error output separately so that the user may read error messages efficiently. System.in is a byte stream that has no character stream features. To use Standard Input as a character stream, wrap System.in within the InputStreamReader as an argument.


InputStreamReader inp= new InputStreamReader (System.in);

8.7 Working with Reader classes:

Java provides the standard I/O facilities for reading text from either the file or the keyboard on the command line. The Reader class is used for this purpose that is available in the java.io package. It acts as an abstract class for reading character streams. The only methods that a subclass must implement are read(char[], int, int) and close(). The Reader class is further categorized into the subclasses.

The following diagram shows a class-hierarchy of the java.io.Reader class.


However, most subclasses override some of the methods in order to provide higher efficiency, additional functionality, or both.

8.7.1 InputStreamReader:

An InputStreamReader is a bridge from byte streams to character streams i.e. it reads bytes and decodes them into Unicode characters according to a particular platform. Thus, this class reads characters from a byte input stream. When you create an InputStreamReader, you specify an InputStream from which, the InputStreamReader reads the bytes.

The syntax of InputStreamReader is written as:

InputStreamReader<variable_name>= new InputStreamReader (System.in)

8.7.2 BufferedReader:

The BufferedReader class is the subclass of the Reader class. It reads character-input stream data from a memory area known as a buffer maintains state. The buffer size may be specified, or the default size may be used that is large enough for text reading purposes. BufferedReader converts an unbuffered stream into a buffered stream using the wrapping expression, where the unbuffered stream object is passed to the constructor for a buffered stream class.

For example the constructors of the BufferedReader class shown as:


BufferedReader (Reader in): Creates a buffering character-input stream that uses a default-sized input buffer.

BufferedReader (Reader in, int sz): Creates a buffering character-input stream that uses an input buffer of the specified size.
BufferedReader class provides some standard methods to perform specific reading operations shown in the table. All methods throw an IOException, if an I/O error occurs.

This program illustrates use of standard input stream to read the user input.


import java.io.*;

public class ReadStandardIO{
public static void main(String[] args) throws IOException{
InputStreamReader inp = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(inp);
System.out.println("Enter text : ");
String str = in.readLine();
System.out.println("You entered String : ");
System.out.println(str);
}
}
Output of the Program:
C:\>javac ReadStandardIO.java
C:\>java ReadStandardIO
Enter text:
this is an Input Stream
You entered String:
this is an Input Stream
C:\>

The streams provide a simple model for reading and writing data. However, streams don't support all the operations that are common with a disk file. Now, we will learn how to work with a file using the non-stream file I/O.

The File class deals with the machine dependent files in a machine-independent manner i.e. it is easier to write platform-independent code that examines and manipulates files using the File class. This class is available in the java.lang package. The java.io.File is the central class that works with files and directories. The instance of this class represents the name of a file or directory on the host file system.

When a File object is created, the system doesn't check to the existence of a corresponding file/directory. If the files exist, a program can examine its attributes and perform various operations on the file, such as renaming it, deleting it, reading from or writing to it.


The constructors of the File class are shown in the table:


Thus the statement can be written as:

File f = new File (“<filename>”);

The methods that are used with the file object to get the attribute of a corresponding file shown in the table.


Whenever the data is needed to be stored, a file is used to store the data. File is a collection of stored information that is arranged in string, rows, columns and lines etc. Further, we will see how to create a file. This example takes the file name and text data for storing to the file.


For creating a new file File.createNewFile ( ) method is used. This method returns a boolean value true if the file is created otherwise return false. If the mentioned file for the specified directory is already exist then the createNewFile () method returns the false otherwise the method creates the mentioned file and return true.


Let‘s see an example that checks the existence of a specified file.


import java.io.*;

public class CreateFile1{
public static void main(String[] args) throws IOException{
File f;
f=new File ("myfile.txt");
if(!f.exists()){
f.createNewFile();
System.out.println("New file \"myfile.txt\" has been created to the current directory");
}
}
}

First, this program checks, the specified file "myfile.txt" is exist or not. If it does not exist then a new file is created with same name to the current location.


Output of the Program

C:\>javac CreateFile1.java
C:\>java CreateFile1
New file "myfile.txt" has been created to the current directory
C:\>

If you try to run this program again then after checking the existence of the file, it will not be created and you will see a message as shown in the output.


C:\>javac CreateFile1.java

C:\>java CreateFile1
the specified file is already exist
C:\>

In Java, it is possible to set dynamic path, which is helpful for mapping local file name with the actual path of the file using the constructing filename path technique.


As seen, how a file is created to the current directory where the program is run. Now we will see how the same program constructs a File object from a more complicated file name, using the static constant File.separator or File.separatorCharto specify the file name in a platform-independent way. If we are using Windows platform then the value of this separator is ' \ '.


Let‘s see an example to create a file to the specified location.


import java.io.*;

public class PathFile{
public static void main(String[] args) throws IOException{
File f;
f=new File ("example" + File.separator + "myfile.txt");
f.createNewFile ();
System.out.println ("New file \"myfile.txt\" has been created to the specified location");
System.out.println ("The absolute path of the file is: " +f.getAbsolutePath ());
}
}

Output of the program:

C:\>javac PathFile.java
C:\>java PathFile
New file "myfile.txt" has been created to the specified location
the absolute path of the file is: C:\Shubh\example\myfile.txt
C:\>


8.8 I/O Streams:

Let‘s now see some I/O streams that are used to perform reading and writing operation in a file. Java supports the following I/O file streams.
 FileInputstream
 FileOutputStream

8.8.1 FileInputstream:

This class is a subclass of Inputstream class that reads bytes from a specified file name. The read () method of this class reads a byte or array of bytes from the file. It returns -1 when the end-of-file has been reached. We typically use this class in conjunction with a BufferedInputStream and DataInputstream class to read binary data. To read text data, this class is used with an InputStreamReader and BufferedReader class. This class throws FileNotFoundException, if the specified file is not exist. You can use the constructor of this stream as:
FileInputstream (File filename);

8.8.2 FileOutputStream:-

This class is a subclass of OutputStream that writes data to a specified file name. The write () method of this class writes a byte or array of bytes to the file. We typically use this class in conjunction with a BufferedOutputStream and a DataOutputStream class to write binary data. To write text, we typically use it with a PrintWriter, BufferedWriter and an OutputStreamWriter class. You can use the constructor of this stream as:
FileOutputstream (File filename);

8.8.3 DataInputStream:-

This class is a type of FilterInputStream that allows you to read binary data of Java primitive data types in a portable way. In other words, the DataInputStream class is used to read binary Java primitive data types in a machine-independent way. An application uses a DataOutputStream to write data that can later be read by a DataInputStream. You can use the constructor of this stream as:
DataInputStream (FileOutputstream finp);
The following program demonstrates how contains are read from a file.

import java.io.*;

public class ReadFile{
public static void main(String[] args) throws IOException{
File f;
f=new File("myfile.txt");
if(!f.exists()&& f.length()<0)
System.out.println("The specified file is not exist");
else{
FileInputStream finp=new FileInputStream(f);
byte b;
do{
b=(byte)finp.read();
System.out.print((char)b);
} while(b!=-1);
finp.close();
}
}

Output of the Program:

C:\>javac ReadFile.java
C:\>java ReadFile this is a text file?
C:\>

This program reads the bytes from file and displays it to the user.


Now we will learn how to write data to a file. As discussed, the FileOutputStream class is used to write data to a file.


Let‘s see an example that writes the data to a file converting into the bytes.


This program first checks the existence of the specified file. If the file exists, the data is written to the file through the object of the FileOutputStream class.


import java.io.*;

public class WriteFile{
public static void main(String[] args) throws IOException{
File f=new File ("textfile1.txt");
FileOutputStream fop=new FileOutputStream (f);
if (f.exists ())
{
String str="This data is written through the program";
fop.write (str.getBytes ());
fop.flush ();
fop.close ();
System.out.println ("The data has been written");
}
else
System.out.println ("This file is not exist");
}

Output of the Program

C:\>javac WriteFile.java
C:\>java WriteFile
The data has been written
C:\>

Now, you will learn how to count the availability of text lines in the particular file. A file is read before counting lines of a particular file. File is a collection of stored information that is arranged in string, rows, columns and lines etc. Try it for getting the lines through the following program


Description of program:

The following program helps you in counting lines of a particular file. At the execution time of this program, it takes a file name with its extension from a particular directory and checks it using exists () method. If the file exists, it will count lines of a particular file otherwise it will display a message ―File does not exists!‖
Description of code:
 FileReader (File file): This is the constructor of FileReader class that is reliable for reading a character files. It constructs a new FileReader and takes a file name that have to be read.
 FileNumberReader (): This is the constructor of FileNumberReader class. It constructs a new line-numbering reader. It reads characters and puts into buffer. By default the numbering of line begins from '0'.

Here is the code of program:


import java.io.*;

public class NumberOfLine{
public static void main(String[] args) {
try{
System.out.println("Getting line number of a particular file example!");
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter file name with extension:");
String str = bf.readLine();
File file = new File(str);
if (file.exists()){
FileReader fr = new FileReader(file);
LineNumberReader ln = new LineNumberReader(fr);
int count = 0;
while (ln.readLine() != null){
count++;
}
System.out.println("Total line no: " + count);
ln.close();
}
else{
System.out.println("File does not exists!");
}
} catch(IOException e){ e.printStackTrace(); }
}
}

Output of program:


Getting line number of a particular file example!

Please enter file name with extension:
AddTwoBigNumbers.shtml
Total line no: 58

Java provides the facility for changing a file timestamp according to the user reliability.

Description of program:

This program helps you in changing a file timestamp or modification time in Java. After running this program it will take a file name and its modification date in 'dd-mm-yyyy' format. Then it will check the given file is exist or not using exists () method. When the file exists, this program will change the date of given file and it will display a message "Modification is successfully!" otherwise it will show ―File does not exists!‖

Description of code:
 setLastModified(long time): This is the method that sets the last modification time of a file or directory and returns Boolean types values either 'true' or 'false'. If it will return a 'true' only when the modification is completely successfully otherwise, it will return 'false'. This method takes following long type data:
 time:
This is the time that has to be modified or set.
 getTime ():
This is the method that returns the number of milliseconds in GMT format like: 23-04-2007.

Here is the code of program:


import java.io.*;

import java.util.*;
import java.text.*;
public class ChangeFileDate{
public static void main(String[] args) {
try{
System.out.println("Change file timestamp example!");
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter file name with extension:");
String str = bf.readLine();
System.out.println("Enter last modified date in 'dd-mm-yyyy' format:");
String strDate = bf.readLine();
SimpleDateFormat sdf= new SimpleDateFormat("dd-MM-yyyy");
Date date = sdf.parse(strDate);
File file = new File(str);
if (file.exists()){
file.setLastModified(date.getTime());
System.out.println("Modification is successfully!");
}
else{
System.out.println("File does not exists!");
}
} catch(Exception e){ e.printStackTrace();
}
}

Output of program:

Change file timestamp example!
Enter file name with extension:
StrStartWith.shtml
Enter last modified date in 'dd-mm-yyyy' format:
23-04-2007
Modification is successfully


8.9 Finding a File:-

To find a file or directory it is very necessary to know the path of the file or directory so that you can access it. If you know the path then it is very easy to work on it. Suppose a situation where a problem comes in front you where you don't know the path of the file, then what will you do? This problem can be solved by using a method getAbsolutePath ().The method getAbsolutePath () should be used where we don't know the exact path of the file.
To find an absolute path of a file, Firstly we have to make a class GetAbsolutePath. Inside this class, define the main method. Inside this method define a File class of java.io package. Inside the constructor of a File class pass the name of the file whose absolute path you want to know. Now call the method getAbsolutePath () of the File class by the reference of File class and store it in a String variable. Now print the string, you will get an absolute path of the file. In this class we have make use of the following things by which this problem can be solved.
 File: It is class in java.io package. It implements Comparable and Serializable interface.
 getAbsolutePath (): It returns the absolute path name in the form of string.

Code of the program is given below:


import java.io.*;

public class GetAbsolutePath{
public static void main(String[] args){
String str = args[0];
File file = new File(str);
String absolutePathOfFirstFile = file.getAbsolutePath();
System.out.println(" The absolute path in first form is " + absolutePathOfFirstFile);
file = new File( "Happy" + File.separatorChar+ str);
String absolutePathOfSecondFile = file.getAbsolutePath();
System.out.println(" The absolute path is " + absolutePathOfSecondFile);
file = new File("Happy" + File.separator + ".." + File.separator + str);
String absolutePathOfThirdFile = file.getAbsolutePath ();
System.out.println (" The absolute path is” + absolutePathOfThirdFile);
}
}

Output of the program

Happy
The absolute path in first form is C:\Smile\Happy
The absolute path is C:\Smile\Happy\Happy
The absolute path is C:\Smile\Happy\..\Happy

8.10 Summary:

In this unit, we learn that what is stream and types of stream. We also learn the concept of input and output stream (The Java Input/Output (I/O) is a part of java.io package). The java.io package contains a relatively large number of classes that support input and output operations.



No comments:

Post a Comment