Input And Output

The Java I/O means Java Input/Output and is a part of java.io package.

Input And Output

The Java I/O means Java Input/Output and is a part of java.io package.

Input And Output

Input And Output

     

Introduction
The Java I/O means Java Input/Output and is a part of
java.io package. This package has a InputStream and OutputStream. Java InputStream is  for reading the stream, byte stream and array of byte stream. It can be used for memory allocation. The OutputStream is used for writing byte and array of bytes. Here, you will know several interfaces provided by the java.io package as follows:

Interfaces and Descriptions:
DataInput This interface can be used for reading byte stream and reconstructing the java primitive data types.
DataOutput This interface can be used for writing the byte stream and converting data from the java primitive data types.
Externalizable This is written in Serializable Stream. It save and store it's contents.
FileFilter It can be used for Filtering the Pathnames.
FilenameFilter This interface used for Filter the Filenames.
ObjectInput This interface used for reading of objects and it extends the DataInput interface. 
ObjectInputValidation This is a Callback interface. It allows the validation of objects within a graph.
ObjectOutput This interface used for writing of objects and it extends the DataOutput interface.
ObjectStreamConstants This interface used for Constants writing into Serialization Objects Stream.
Serializable This interface implementing in the java.io.Serializable interface.

Classes and Descriptions:
BufferedInputStream It used for creating an internal buffer array. It supports the mark and reset methods.
BufferedOutputStream This class used for writes byte to output stream. It implements a buffered output stream.
BufferedReader This class provides read text from character input stream and buffering characters. It also reads characters, arrays and lines.
BufferedWriter This class provides write text from character output stream and buffering characters. It also writes characters, arrays and lines.
ByteArrayInputStream It contains the internal buffer and read data from the stream.
ByteArrayOutputStream This class used for data is written into byte array. This is implement in output stream class. 
CharArrayReader It used for char input stream and implements a character buffer.
CharArrayWriter This class also implements a character buffer and it uses an writer.
DataInputStream This class reads the primitive data types from the input stream in a machine format.
DataOutputStream This class writes the primitive data types from the output stream in machine format.
File This class shows a file and directory pathnames.
FileDescriptor This class uses for create a FileInputStream and FileOutputStream.
FileInputStream It contains the input byte from a file and implements an input stream.
FileOutputStream It uses for writing data to a file and also implements an output stream.
FilePermission It provides the permission to access a file or directory.
FileReader This class used for reading characters file.
FileWriter This class used for writing characters files.
FilterInputStream This class overrides all methods of InputStream and contains some other input stream.
FilterOutputStream This class overrides all methods of OutputStream and contains some other output stream.
FilterReader It reads the data from the filtered character stream.
FilterWriter It writes data from the filtered character stream.
InputStream This class represents an input stream of bytes.
InputStreamReader It reads bytes and decodes them into characters.
LineNumberReader This class has a line numbers
ObjectInputStream This class used for recover the object to serialize previously. 
ObjectInputStream.GetField This class access to president fields read form input stream.
ObjectOutputStream This class used for write the primitive data types and also write the object to read by the ObjectInputStream.
ObjectOutputStream.GetField This class access to president fields write in to ObjectOutput.
ObjectStreamClass Serialization's descriptor for classes.
ObjectStreamField This class describes the serializable field.
OutputStream This class represents an output stream of bytes.
OutputStreamWriter It writes bytes and decodes them into characters.
PipedInputStream In this class the data bytes are written into piped output stream. This class also connected into a piped output stream.
PipedOutputStream This class also communicates the piped input stream into piped output stream. It creates communication between both.
PipedReader It is a piped character-input stream.
PipedWriter It is a piped character-output stream.
PrintStream This class adds the functionality of another output stream.
PrintWriter This class adds the functionality of another input stream.
PushbackInputStream It also include the another function of input stream. Such as: "push back" or "unread" one byte.
PushbackReader This is a character stream reader and reads the data push back into the stream.
RandomAccessFile It supports both reading and writing to a random access file.
Reader It used for reading character stream.
SequenceInputStream It represents the logical concatenation of other input stream.
SerializablePermission This is a serializable permission class.
StreamTokenizer It takes an input stream and parse it into "tokens" . The token to be allowed at the read time.
StringReader This is a character string class. It has character read source.
StringWriter This is also a character string class. It uses to shows the output in the buffer.
Writer It uses for writing to character stream.

Exceptions for java.io package:
CharConversionException It provides detail message in the catch block to associated with the CharConversionException
EOFException This exception indicates the end of file. When the file input stream to be end then EOFException to be occuted.
FileNotFoundException When the open file's pathname does not find then this exception to be occured.
InterruptedIOException When the I/O operations to interrupted from any causes then it becomes.
InvalidClassException Any problems to be created with class, when the Serializing runtime to be detected. 
InvalidObjectException When the de-serialized  objects failed then it occurs.
IOException When the I/O operations to be failed then it occurs.
NotActiveException The Serialization or deserialization operations are not active then it occurs.
NotSerializableException This exception when the instance is required to a Serializable interface.
ObjectStreamException This is a supper class of all exception class. It used for specific to Object Stream Classes.
OptionalDataException When the reading data operations to failed then it these exception occurs. It is belonging to the serialized object
StreamCorruptedException It thrown when the control information that was read form an object stream vioaltes internal consistency checks.
SyncFaieldException The sync operation is failed then SyncFaieldException to be occure.
UnsupportedEncodingException The Character Encoding is not supported.
UTFDataFormatException A molformed UTF-8 has been read in a data input stream, it implemented by data input interface.
WriteAbortedException In this exception to be thrown by the ObjectStreamException during a write operating.

Read Text from Standard IO: Java provides the standard I/O facilities for reading text through either the file or keyboard in command line. This program illustrates you how to use standard input to read the user input..

In this section, you will see how the standard I/O is used to input any thing by the keyboard or a file. This is done using the readLine() method which is the method of the BufferedReader class.

BufferedReader : 
The BufferedReader class is the subclass of the FilterReader class. BufferedReader class maintains the buffer and buffer state. BufferedReader class supports the read() and readLine() method for input text from a character-input stream. The buffer size may be specified but the default buffer size is enough for most purposes because the default buffer size of 8192 chars can be overridden by the creator of the stream.

In this program, as you can see that the instance variable in of the BufferedReader class which reads a single line of text from the input stream.

Here is the code of the program :

import java.io.*;

public class ReadStandardIO{
  public static void main(String[] args) throws IOException{
  BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  System.out.println("Enter text : ");
  String str = in.readLine();
  System.out.println("You entered String : ");
  System.out.println(str);
  }
}

Filter Files in Java: The Filter File Java example code provides the following functionalities:

  • Filtering the files depending on the file extension provided by the user
      
  • User provides the file extension and then program lists all the matching files found

Program accepts directory name and file extension from user and displays the files present in the directory.

Program begins with import statement java.io.*; package, which is required for any input/output operations.

Classes Defined in the program:

OnlyExt
The constructor of the class takes file extension as parameter and then prefix it with "*." and assign into the global variable ext. The OnlyExt class implements FilenameFilter interface, so we have to implement the abstract method accept() defined in the FilenameFilter interface. The accept() method tests if a specified file should be included in a file list.

FilterFiles: 
The FilterFiles contains the public static void main(String args[]), which is the entry point of our program. The program first accepts directory name and file extension from the user and creates the object of OnlyExt class passing file extension as constructor parameter.

Here is the code of the program :

import java.io.*;

class OnlyExt implements FilenameFilter{
  String ext;

  public OnlyExt(String ext){
  this.ext="." + ext;
  }
  
  public boolean accept(File dir,String name){
  return name.endsWith(ext);
  }
}

public class FilterFiles{
  public static void main(String args[]) throws IOException{
  BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  System.out.println("Please enter the directory name : ");
  String dir = in.readLine();
  System.out.println("Please enter file type : ");
  String extn = in.readLine();
  File f = new File(dir);
  FilenameFilter ff = new OnlyExt(extn);
  String s[] = f.list(ff);

  for (int i = 0; i < s.length; i++)
  {
  System.out.println(s[i]);
  }
  }
}

Java read file line by line: In the section you will learn how to write java program to read file line by line. We will use the DataInputStream class to Read text File Line by Line.

Class DataInputStream
A data input stream is use to read primitive Java data types from an underlying input stream in a machine-independent way. An application uses a data output stream to write data that can later be read by a data input stream.

Data input streams and data output streams represent Unicode strings in a format that is a slight modification of UTF-8. (For more information, see X/Open Company Ltd., "File System Safe UCS Transformation Format (FSS_UTF)", X/Open Preliminary Specification, Document Number: P316. This information also appears in ISO/IEC 10646, Annex P.) Note that in the following tables, the most significant bit appears in the far left-hand column.

BufferedReader

Read text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.

In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. For example,

 BufferedReader in
   = new BufferedReader(new FileReader("foo.in"));
 
will buffer the input from the specified file. Without buffering, each invocation of read() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient.

Programs that use DataInputStreams for textual input can be localized by replacing each DataInputStream with an appropriate BufferedReader.

Here is the code of java program to Read text File Line by Line:

import java.io.*;
class FileRead 
{
 public static void main(String args[])
  {
  try{
  // Open the file that is the first 
  // command line parameter
  FileInputStream fstream = new FileInputStream("textfile.txt");
  // Get the object of DataInputStream
  DataInputStream in = new DataInputStream(fstream);
  BufferedReader br = new BufferedReader(new InputStreamReader(in));
  String strLine;
  //Read File Line By Line
  while ((strLine = br.readLine()) != null) {
  // Print the content on the console
  System.out.println (strLine);
  }
  //Close the input stream
  in.close();
  }catch (Exception e){//Catch exception if any
  System.err.println("Error: " + e.getMessage());
  }
  }
}

Create File in Java: Whenever there need to be store data, you have to create a file into some directory. In this program, we will see how to create a file. This example takes the file name and text data for adding into the file.

For creating a new file File.createNewFile() method has been 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. The constructor of the FileWriter class takes the file name which has to be buffered by the BufferedWriter stream. The write() method of BufferedWriter class is used to create the file into specified directory.

Following code  write data into new file: 

out.write(read_the_Buffered_file_name);

Following code creates the object of FileWriter and BufferedWriter

FileWriter fstream = new FileWriter(file_name);
BufferedWriter out = new BufferedWriter(fstream);


Here is the code of program : 

import java.io.*;

public class CreateFile{

  public static void main(String[] args) throws IOException{
  BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  System.out.print("Please enter the file name to create : ");
  String file_name = in.readLine();
  File file = new File(file_name);
  boolean exist = file.createNewFile();
  if (!exist)
  {
  System.out.println("File already exists.");
  System.exit(0);
  }
  else
  {
  FileWriter fstream = new FileWriter(file_name);
  BufferedWriter out = new BufferedWriter(fstream);
  out.write(in.readLine());
  out.close();
  System.out.println("File created successfully.");
  }
  }
}

Copying one file to another: This example illustrates how to copy contents from one file to another file. This topic is related to the I/O (input/output) of java.io package. 0

In this example we are using File class of java.io package. The File class is an abstract representation of file and directory pathnames. This class is an abstract, system-independent view of hierarchical pathnames. An abstract pathname has two components:

  1. An optional system-dependent prefix string,
    such as a disk-drive specifier, "/" for the UNIX root directory, or "\\" for a Win32 UNC pathname, and
  2. A sequence of zero or more string names.

Explanation

This program copies one file to another file. We will be declaring a function called copyfile which copies the contents from one specified file to another specified file. 1

copyfile(String srFile, String dtFile)

The function copyfile(String srFile, String dtFile) takes both file name as parameter. The function creates a new File instance for the file name passed as parameter

File f1 = new File(srFile);
File f2 = new File(dtFile);  2

and creates another InputStream instance for the input object and OutputStream instance for the output object passed as parameter

InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2); 

and then create a byte type buffer for buffering the contents of one file and write to another specified file from the first one specified file. 3

// For creating a byte type buffer
byte[] buf = new byte[1024];
// For writing to another specified file from buffer buf
out.write(buf, 0, len);

Code of the Program : 

import java.io.*;

public class CopyFile{
  private static void copyfile(String srFile, String dtFile){
  try{
  File f1 = new File(srFile);
  File f2 = new File(dtFile);
  InputStream in = new FileInputStream(f1);
  
  //For Append the file.
//  OutputStream out = new FileOutputStream(f2,true);

  //For Overwrite the file.
  OutputStream out = new FileOutputStream(f2);

  byte[] buf = new byte[1024];
  int len;
  while ((len = in.read(buf)) > 0){
  out.write(buf, 0, len);
  }
  in.close();
  out.close();
  System.out.println("File copied.");
  }
  catch(FileNotFoundException ex){
  System.out.println(ex.getMessage() + " in the specified directory.");
  System.exit(0);
  }
  catch(IOException e){
  System.out.println(e.getMessage());  
  }
  }
  public static void main(String[] args){
  switch(args.length){
  case 0: System.out.println("File has not mentioned.");
  System.exit(0);
  case 1: System.out.println("Destination file has not mentioned.");
  System.exit(0);
  case 2: copyfile(args[0],args[1]);
  System.exit(0);
  default : System.out.println("Multiple files are not allow.");
  System.exit(0);
  }
  }
}

Serializing an Object in Java: In this section, you will learn how to Serialize an Object in java. Serialization refers to the method of saving the object's sate into the file store or  database. The serialized objects are JVM independent and can be re-serialized by any JVM. In this case the "in memory" java objects state are converted into a byte stream. This type of the file can not be understood by the user. It is a special types of object i.e. reused by the JVM (Java Virtual Machine). 4

This example shows you how to serialize any objects. This program takes a file name and then serialize the object. This file is machine understandable.

Default serialization mechanism for an object writes the class of the object, the class signature, and the values of all non-transient and non-static fields.

ObjectOutput ObjOut = new ObjectOutputStream(new FileOutputStream(f));
Above code has been used to create the instance of the ObjectOutput class with the ObjectOutputStream() constructor which takes the instance of the FileOuputStream as a parameter.  5

The ObjectOutput interface is used by implementing the ObjectOutputStream class. The ObjectOutputStream is constructed to serialize the object. 

writeObject():
Method writeObject() writes an object to the given stream.

Here is the code of program: 6

import java.io.*;

public class SerializingObject{
  public static void main(String[] args) throws IOException{
  BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  System.out.print("Please enter File name : ");
  String file = in.readLine();
  System.out.print("Enter extention : ");
  String ext = in.readLine();
  String filename = file + "." + ext;
  File f = new File(filename);
  try{
  ObjectOutput ObjOut = new ObjectOutputStream(new FileOutputStream(f));
  ObjOut.writeObject(f);
  ObjOut.close();
  System.out.println("Serializing an Object Creation completed successfully.");
  }
  catch(IOException e){
  System.out.println(e.getMessage());
  }
  }
}

Deserializing an Object in java: Here, you will learn how to De-serialize the Java object. This means, converting the serialized object into in-memory java object. This program shows how to read any data or contents from the serialized object or file. It takes a file name and then converts into java object. If any exception occurs during reading the serialized file, it is caught in the catch block.

ObjectInputStream obj = new ObjectInputStream(new FileInputStream(f));
Above code of the program creates the instance of the ObjectInputStream class to deserialize that file which had been serialized by the ObjectOutputStream class. The above code creates the instance using the instance of the FileInputStream class which holds the specified file object which has to be deserialized because the ObjectOutputStream() constructor needs the input stream.

readObject():
Method readObject() reads the object and restore the state of the object. This is the method of the ObjectOutputStream class and methods of ObjectOutputStream class helps to traverse the object. 7

Here is a code of program :

import java.io.*;

public class DeserializingObject{
  public static void main(String[] args) throws IOException{
  BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  System.out.print("Enter File name : ");
  String file = in.readLine();
  System.out.print("Enter extention : ");
  String ext = in.readLine();
  String filename = file + "." + ext;
  File f = new File(filename);
  try{
  ObjectInputStream obj = new ObjectInputStream(new FileInputStream(f));
  System.out.println("The text : "+  obj.readObject());
  obj.close();
  System.out.println("Deserializing Operation Completly Successfully.");
  }
  catch(ClassNotFoundException e){
  System.out.println(e.getMessage());
  }
  catch(FileNotFoundException fe){
  System.out.println("File not found ");
  }
  }
}

to go in more details about I/O plz go through "http://www.roseindia.net/java/example/java/io/".