^

DataInputStream & DataOutputStream Classes

The DataInputStream class implements DataInput interface and extends class FilterInputStream . Whereas the DataOutputStream class implement DataOutput interface and inherits class FilterOutputStream . Using these classes, you can read and write binary representation of Java primitive values to and from an underlying stream. Both classes consists of read and write methods for all data types in Java (as shown below) and all methods throw IOException . if the stream does not contain the correct number of bytes to be read.

DataInputStream Class

Constructor
  • DataInputStream (InputStream Object)
Methods
  1. boolean readBoolean() throws IOException
  2. char readChar() throws IOException
  3. byte readByte() throws IOException
  4. short readShort() throws IOException
  5. int readint() throws IOException
  6. long readLongo throws IOException
  7. float readFloat() throws IOException
  8. double readDouble() throws IOException
  9. String readLine() throws IOException
  10. String readUTF() throws IOException

DataOutputStream Class

  • DataOutputStream (OutputStream Object)
Methods
  1. void writeBoolean() throws IOException
  2. void writeChar() throws IOException
  3. void writeByte(byte b) throws IOException
  4. void writeShort(Short s) throws IOException
  5. void writeInt(int i) throws IOException
  6. void writeLong(long i) throws IOException
  7. void writeFloat(float f) throws IOException
  8. void writeDouble(double d) throws IOException
  9. void writeChars(String str) throws IOException
  10. void writeUTF(String str) throws IOException
According to the above diagram, to write binary data to a file, you the FileOutputStream object to DataOutputStream object and calle methods. For example:
     FileOutputStream fos = new FileOutputStream ("data.txt'); 
     DataOutputStream dos = new DataOutputStream (fos); // chaining
              
Similarly, while reading you need to chain the FileInputStream object to DataInputStream object and then call its read() methods to read data values from file. For example:
     FileInputStream fis = new FileInputStream ("data.txt"); 
     DataInputStream dis = newDataInputStream (fis); //chaining
            
Implementation
The following program uses the recently discussed classes to write and read primitive values in a file.
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class DataInOutStream {

    public static void main(String[] args) 
    {
      	int productId = 1;
        String productName = "Laptop";
        int quantity = 2;
        float price = 100000;

        int productId2 = 2;
        String productName2 = "Byke";
        int quantity2 = 3;
        float price2 = 240000;

        try {
           
            FileOutputStream fos = new FileOutputStream("products.txt",true);//opening file in append mode
            DataOutputStream dos = new DataOutputStream(fos);
            	
            //Write ist Record
            dos.writeInt(productId);
            dos.writeUTF(productName);
            dos.writeInt(quantity);
            dos.writeFloat(price);
            	
            //write IInd Record
            dos.writeInt(productId2);
            dos.writeUTF(productName2);
            dos.writeInt(quantity2);
            dos.writeFloat(price2);

            dos.flush();
            dos.close();

            FileInputStream fis = new FileInputStream("products.txt");
            DataInputStream dis = new DataInputStream(fis);

            // Reading Records from file
         try{
            while(true)
          {
            productId = dis.readInt();
            System.out.println("Id: " + productId);
             productName = dis.readUTF();
            
            System.out.println("Name: " + productName);
            quantity = dis.readInt();
            System.out.println("Quantity: " + quantity);
            price = dis.readFloat();
            System.out.println("Price: " +price);
           }
         }
         catch(Exception ex){}

          dis.close();
        } catch (IOException e) { e.printStackTrace();     }
    }
}
       
       OUTPUT
			Id: 1
			Name: Laptop
			Quantity: 2
			Price: 100000.0
			Id: 2
			Name: Byke
			Quantity: 3
			Price: 240000.0
       

Character Streams

Byte Streams deals in ASCII Characters that range from 0 to 255. Th using byte streams, we can read and write the data having ASCII val, It can be said that text in english language can be read and written h. languages than english, are not allowed to use with byte streams. To o the language problem, in JDK1.1 version, designers introduced character Character streams operate on Unicode Characters. ASCII code is a Unicode Characters set.

Unicode

Unicode provides a unique number for every character, no matter what the platform, no matter what the program, no matter what the language is. Unicode supports many operating systems, all modern browsers etc. Unicode enables a single software product or a single website to be targeted across multiple platforms, languages and countries without re-engineering it and allows data to be transported through many different systems without corruption.

Why Use Character Streams

The Primary advantage of using character streams is that they make it easy to write programs that are not dependent on a specific character encoding and are therefore easy to internationalize. Java stores strings in unicode. A second advantage of character streams is that they are potentially much more efficient than byte streams. Byte stream follows byte-at-a-time read and write operations, whereas character stream classes follow buffer-at-a-time read and write operations.

Readers and Writers Inheritance Hierarchy

java.io package provides an inheritance hierarchy of classes to work with character streams. The abstract classes Reader and Writer are the root of the inheritance hierarchies for handling characters shown as follows:

Partial Reader Stream Inheritance Hierarchy

Partial Writer Stream Inheritance Hierarchy

Reader and Writer Classes

Reader Class

Reader class is an abstract class. It consists of the following methods unicode characters: -
  1. int read() throws IOException.
  2. int read(char array() throws IOException.
  3. int read(char array[], int startIndex, int N) throws IOException
Consider that the read() method reads the characters as int in the range 0 to 65535. It returns - 1 when end of the stream is found.

Writer Class

Writer class is also an abstract class, which cannot be instantiate. It consists following methods for writing unicode characters.
  1. void write(int ch) throws IOException.
  2. void write(String str) throws IOException
  3. void write(char[] buffer, int startIndex, int N) throws IOException
  4. void write(String str, int startIndex, int N) throws IOException
First write(int ch) method writes a single character. The character to be written is contained in the 16 low order bits of the given integer value. The 16 higher bits are ignored.
The other write() methods write the characters from array of characters or strings.
  1. void flush() throws IOException
  2. void close() throws IOException
Its close() method clears the character stream to get the resources free for reuse. Closing the character OutputStream automatically flushes the stream. A character output Stream can also be flushed manually with flush() method.

FileReader and FileWriter Classes

FileReader Class

The FileReader class inherits InputStreamReader class, which furth Reader class. The FileReader class is meant for reading text files, because it reads a stream of characters. When you instantiate FileReader class, a connection is created to the specified file for reading the data.

Constructor

  1. FileReader (String fileName) throws FileNotFoundException
  2. FileReader (File fileObject) throws FileNotFoundException
  3. FileReader (FileDescriptor descObject) throws FileNotFoundException.
The above Constructors creates FileReader object by opening a connection to an actual file,the file can be specified by its name (String), through a File object or using aFileDescriptor object. If the file does not exist or is a directory rather than a file or someother reasons cannot be opened for reading, then FileNotFound-Exception is thrown.

FileWriter Class

The FileWriter Class inherits OutputStream Writer class, which further inherits Writer class as shown in Figure-7 earlier. The File Writer class is meant for writing Stream of characters into Files. When you instantiate the File Writer class, then a connection is created to the specified file for writing the text/character data.

Constructors

  1. File Writer (String fileName) throws IOException
  2. File Writer (File fileObject) throws IOException.
  3. File Writer (FileDescriptor descObject) throws IOException.
The above constructors creates File Writer object by opening a connection to an actual file, the file can be specified by its name (String), through a File object or using a FileDescriptor object. Note that you can create a stream connection with a regular file only and not with a directory. An IOException is thrown, if the specified file object is a directory rather than a file, if it does not exist or cannot be created or if it cannot be used to write for some other reason.
Implementation
The following program shows the use of FileReader and FileWriter classes to copy the text from one file to another.
import java.io.*;
public class readerWriterClasses 
{
public static void main(String[] args)  
	{
	try{
		copyTextFile();
	   }
	catch(FileNotFoundException ex){ex.printStackTrace();}
	catch(IOException exp){exp.printStackTrace();}
	}
	static void copyTextFile()throws FileNotFoundException,IOException
	{
		File src=new File("real.txt");
		FileReader read=new FileReader(src);
		FileWriter write=new FileWriter("realjava.txt");

		int c;
		while(true)
		{
			c=read.read();//reading from file
			if(c==-1)
				break;
			write.write(c);// writing in file
			System.out.print((char)c); //print on Screen
		}
		read.close();
		write.close();
		System.out.println("\n File Copied......");
	}
}
       
           File Copied
       

About the Author
Rajesh K. Bansal (SCJP-Sun Certified Java Programmer)
20 Years experience in Training & Development. Founder of realJavaOnline.com, loves coding in Java(J2SE, J2EE), C++,PHP, Python, AngularJS, Android,MERN Stack(MongoDB,Express,ReactJS,NodeJS). If you like tutorials and want to know more in depth about Java , buy his book "Real Java" available on amazon.in.
#Email : bcebti@gmail.com #Contact : 98722-46056
Available on Amazon
Card image cap
Under the guidance of Founder & Author of "realJavaOnline.com". M:9872246056
Card image cap