Files I/O

Input is any information which a program needs to complete its execution. Program can use any kind of user interface whether it is Character User Interface (CUI) or Graphical User Interface (GUI) for accepting input from the user.

The source of the information could be Input Devices such as keyboard, mouse, and file in the same computer or in other location in a network.

Output is any information which a program conveys to the user. Program can use any kind of user interface such as GUI or CUI for displaying the output for the user.

The output of a program can be send to output devices such as monitor, printer, speakers or any file either in the same computer or to other computer in the network.

So far we have been using System.out.println() method for printing the messages on the screen (or console).

In this chapter, we will be learning about the various types of input/output operation we can perform in java. We will be learning about the stream classes and their usage.

Using Command-line Argument

You must have noticed the syntax of the main method in every program which is written like


public static void main(String args[])
{
} 
// Or
public static void main(String…args)
{
}

We already know the importance of the main method and the public static modifier associated with it. However what is the significance of writing String args[] or String…args as a parameter of main method? The answer to this question is, it is written for accepting command line argument.

Command line arguments are the arguments passed to a program while launching the program. Creating a varargs in the main method allows us to pass any number of arguments when the application is launched.

The arguments passed from the command prompt are always a string therefore it the varargs in the main method can only be string. However inside the program they can be converted into specific type.

The command line arguments can be used for passing some configuration details when it is launched.

For understanding command line argument, you may consider a command mkdir which is used to create directory in the file system.

The mkdir command is followed by a name of the directory while mkdir command is being launched. Here the mkdir command can be considered as a java program and the name of the directory can be considered as the command line argument.

Let us understand the command line arguments with an example.


public class PrintNames 
{  
	public static void main(String…args)  
	{   
		System.out.println("Welcome Students");     
		for(String names : args)   
		{   
		 System.out.println("Hi,  "+names);   
		}  
	} 
}

Compile and run the code like below


Compile: - javac PrintNames.java in CMD
Run:- java PrintNames John Peter Marry 

// Output:  
Welcome Students 
Hi, John  
Hi, Peter 
Hi, Marry

As we can see while running the above program we have passed three arguments John, Peter and Marry which is being stored in the string varargs args. Then by using enhanced for loop we looped through the array args and print all the names passed.

Let us take another example of adding numbers passed through command line argument.


public class Sum 
{  
public static void main(String args[])  
{  
 //a local variable must be initialized before use.  
 int sum=0;   
for(String num : args)   
{   
 sum=sum+Integer.parseInt(num);  
 }  
 System.out.println("Sum of the numbers : "+sum); 
 } 
} 

Compile and run the code


Compile:- javac Sum.java
Run:- java Sum 15 20 30 60 
Output:- Sum of the number : 125 

In the above example Integer.parseInt() method has been used to convert a string into integer

Streams

Streams are objects that represent sources and destinations of data. Streams that are sources of data can be read from, and streams that are destinations of data can be written to.

A stream in Java is an ordered sequence of bytes of undetermined length. Streams are ordered and in sequence so that the java virtual machine can understand and work upon the stream.

Streams can be categorized into two basic types:

  • Input Stream: A program uses an input stream to read data from a source, one item at a time.
  • Output Stream: A program uses an output stream to write data to a destination, one item at time.
streams-java

A Java program is reasonably well served by its default state when execution begins. Three streams are setup and ready to go.

There are two output streams, identified by the objects System.out and System.err, and one input stream, identified by the object System.in. These objects are defined as public static data fields in the System class of the java.lang package.

Variable

Type

Purpose

err

PrintStream

The "standard error" output stream. This stream is already open and ready to accept output data.

out

PrintStream

The "standard output" stream. This stream is already open and ready to accept output data.

In

InputStream

The "standard input" stream. This stream is already open and ready to supply input data.

As noted in the table, the streams are "open and ready" when a Java program begins execution. To use these objects in a program, they must be prefixed with "System." to identify where they are defined.

The err and out objects are instances of the PrintStream class and the in object is an instance of the InputStream class. As you might guess, methods in these classes provide the means to input or output data.

As well, the default devices for these streams are the keyboard for input and monitor for output. Two output streams are provided to separate "normal" output from error messages.

The Standard Output Stream (System.out)

We have been using the standard output stream in the form of System.out.println() in our samples and examples.

The method println() is called via an instance of the PrintStream class, in this case the object variable out which has been publicly declared in System class of the java.lang package.

As the out variable is declared as static in the System class it can has to be accessed by the class name. That is why we use System.out.

The PrintStream class provides two methods print() and println() for output. Note that the print() and println() methods are overloaded. They can accept any of the primitive data types as arguments, as well as character arrays or strings.

If println() is called without an argument it serves only to terminate the current line by outputting a newline character ('\n').

The method print() outputs its argument as a series of characters without automatically sending a newline character. On some systems, the print()must be followed by the flush() to force characters to print immediately.


public class Demo 
{ 
	public static void main(String ar[]) 
	{   
		System.out.print("Hello, ");   
		System.out.println("how are you?");  
		System.out.print("Exiting"); 
	}
} 


// Output: 
Hello, how are you? Exiting 

The Standard Input Stream (System.in)

Unfortunately, the behavior of Java programs is not quite as clean for the standard input stream as it is for the standard output stream. The object variable "in" is defined in the System class as an instance of the InputStream class. As is, the standard input stream is setup to read raw, unbuffered bytes from the keyboard. Such low-level control may be necessary in some cases, but the result is inefficient and provides poor formatting of input data.

For example, it forces us to deal explicitly with keystrokes such as "backspace" and "delete".

In order to easily use InputStreams it is often useful to de?ne a wrapping BufferedReader.

As an example:


BufferedReader reader =new BufferedReader(new InputStreamReader(System.in));

The object System.in appears above as an argument to the constructor of the InputStreamReader class. The resulting object — an instance of the InputStreamReader class — in turn appears as an argument to the constructor of the BufferedReader class. A reference to the instantiated object is assigned to the object variable reader.

Now, we have access to the standard input stream via the object variable reader which is an instance of the BufferedReader class in the java.io package.

So, the methods of the BufferedReader class can be used to read from input streams now.

The BufferedReader class has various methods for reading the inputs from the input streams. These methods are either overridden methods of InputStream class or its own.

List of Common methods present in BufferedReader class

Method

Description

int available()

Return the number of bytes available to read.

void close()

Closes the stream

Int read(byte []arr)

Reads as many bytes as arr. length, stores them in the array,returns number of bytes read

String readLine()

Reads in the stream up to a '\n' and return as String

long skip(long n)

skips n characters

The read() and readLine() methods methods throws a checked exception IOException. Therefore, must be handled in the program.

Example:
Let us create a program to accept employee name, age from the user and display the same using BufferedReader class. In order to use BufferedReader and InputStreamReader class we must import the java.io package


package EMS;
import java.io. * ;
class Employee {
	private String EmployeeName;
	private int Age;
	public String getEmployeeName() {
		return EmployeeName;
	}
	public void setEmployeeName(String EmployeeName) {
		this.EmployeeName = EmployeeName;
	}
	public int getAge() {
		return Age;
	}
	public void setAge(int Age) {
		this.Age = Age;
	}
}

public Class MainClass {
	public static void main(String ar) {
		InputStreamReader isr = new InputStreamReader(System. in );
		BufferedReader br = new BufferedReader(isr);
		/*    Can also be written as    
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 
		*/
		String name;
		Int age;
		//careate instance of Employee
		Employee e = new Employee();
		try {
			// read input in local variables 
			System.out.println("Enter Employee's Name: ");
			Name = br.readLine();
			System.out.println("Enter Employee's Age: ");
			age = Integer.parseInt(br.readLine());

			//set the values for fields EmployeeName and Age of Employee class. 

			e.setEmployeeName(name);
			e.setAge(age);

			//print the field's data for object e of employee class.
			System.out.println("Employee's Details");
			System.out.println("Employee Name: " + e.getEmployeeName());
			System.out.println("Employee Age: " + e.getAge());
		}
		catch(IOException ex) {
			System.out.println(ex.getMessage());
		}

	}
}

Using java.util.Scanner

The java.util.Scanner class is a simple text scanner which can parse primitive types and strings using regular expressions.

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.

For example, this code allows a user to read a number from System.in:


Scanner sc = new Scanner(System.in); 
int i = sc.nextInt(); 

A scanner class may be instantiated by any one of the following constructor.

  • Scanner(File source) This constructs a new Scanner that produces values scanned from the specified file.
  • Scanner(File source, String charsetName) This constructs a new Scanner that produces values scanned from the specified file.
  • Scanner(InputStream source) This constructs a new Scanner that produces values scanned from the specified input stream.
  • Scanner(InputStream source, String charsetName)This constructs a new Scanner that produces values scanned from the specified input stream.
  • Scanner(Readable source) This constructs a new Scanner that produces values scanned from the specified source.
  • Scanner(ReadableByteChannel source) This constructs a new Scanner that produces values scanned from the specified channel.
  • Scanner(ReadableByteChannel source, String charsetName) This constructs a new Scanner that produces values scanned from the specified channel.
  • Scanner(String source) This constructs a new Scanner that produces values scanned from the specified string.

List of common methods of the Scanner class

  • byte nextByte() This method scans the next token of the input as a byte.
  • int nextInt() This method scans the next token of the input as an int.
  • float nextFloat() This method scans the next token of the input as a float.
  • double nextDouble() This method scans the next token of the input as a double.
  • long nextLong() This method scans the next token of the input as a long.
  • String next() This method finds and returns the next complete token from this scanner.
  • boolean hasNext() This method returns true if this scanner has another token in its input.
  • boolean hasNextInt() This method returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method.

Example:


import java.util.*;
public class ScannerSum
{ 
	public static void main(String[] args)  
	{ 
		Scanner console = new Scanner(System.in); 
		System.out.print("Enter three numbers: "); 
		int num1 = console.nextInt(); 
		int num2 = console.nextInt(); 
		int num3 = console.nextInt();
		int sum = num1 + num2 + num3;
		System.out.println("The sum is " + sum); 
	} 
} 

Output will be the sum of three numbers entered by the user.

File Streams

The streams used most often are the standard input (the keyboard) and the standard output (the CRT display). Alternatively, standard input can arrive from a disk file using "input redirection", and standard output can be written to a disk file using "output redirection".

Java provides a standard way of reading from and writing to files. The java.io package contains classes which can be used to read and write files and other sources.

Most of the classes implement sequential access streams. The sequential access streams can be divided into two groups: those that read and write bytes and those that read and write Unicode characters.

Each sequential access stream has a specialty, such as reading from or writing to a file, filtering data as its read or written, or serializing an object.

There are two types of file stream namely FileInputStream (subclass of InputStream) and FileOutputStream (subclass of OutputStream) one for input (reading from a file) and another for output (writing to a file).

  • FileInputStream class is used to create an input stream with a file to read data from the specified file. The data can be read using FileReader class.
  • FileOutputStream class is used to create an output stream with a file to write the data to the specified file. The data can be written to the file using FileWriter class.
  • Byte Streams: Byte streams perform input and output of 8-bit bytes. They read and write data one byte at a time. Using byte streams is the lowest level of I/0, so if you are reading or writing character data the best approach is to use character streams. Other stream types are built on top of byte streams.
  • Character Streams: All character stream classes are descended from Reader and Writer. We are going to use the Reader and Writer classes that perform file I/0, FileReader and FileWriter.

Reading from a file using FileInpuStream Class

The FileInputStream class is the subclass of InputStream class and provides a stream of bytes to read from a specified file. Reading from a file using FileInputStream involves three steps. Create stream, read the data and close the stream.

List of Common methods of FileInputStream class.

  • int available() Returns the number of remaining bytes that can be read from this input stream .
  • int read() Reads a byte of data from this input stream.
  • int read(byte[] b) Reads up to b.length bytes of data from this input stream into an array of bytes.
  • int read(byte[] b, int off, int len) Reads up to len bytes of data from this input stream into an array of bytes.
  • long skip(long n) Skips over and discards n bytes of data from the input stream.

Here is an example which reads data from a file data.txt with the help of various methods provided by the FileInputStream class.


import java.io. * ;

class ReadData {
	public void read1() throws IOException {
		/*reading all content of a file using read(byte[] b) method */
		FileInputStream fin = new FileInputStream("data.txt");
		// Create a byte array   
		byte[] b = new byte[fin.available()];
		// Read data into the array    
		fin.read(b);
		for (int i = 0; i < b.length; i++) {
			System.out.print((char) b[i]);
		}
		fin.close();
	}
	public void read2() throws IOException {
		/*reading all content of a file using read() method */
		int k = 0;
		FileInputStream fin1 = new FileInputStream("data.txt");
		System.out.println("\n\nSecond way\n");
		// Read till the end of file    
		while ((k = fin1.read()) != -1) {
			System.out.print((char) k);
		}
		fin1.close();
	}
	public void read3() throws IOException {
		/*reading all content of a file using read(byte[] b,int offset,int len) method */
		FileInputStream fin2 = new FileInputStream("data.txt");
		byte b1[] = new byte[fin2.available()];
		fin2.read(b1, 0, b1.length);
		System.out.println("\n\nThird way\n");
		for (int i = 0; i <b1.length; i++) {
			System.out.print((char) b1[i]);
		}
		fin2.close();
	}
	public static void main(String args[]) throws Exception {
		/*either of methods read1(), read2, or read3 can be called */
		ReadData rd = new ReadData();
		rd.read1();
	}
}

Writing to a file using FileOutputStream Class

The FileOutputStream class is the subclass of OutputStream class and provides a stream of bytes to write bytes to a specified file.

Writing bytes to a file using FileOutputStream involves three steps. Create stream, write the bytes and close the stream.

List of Common methods of FileOutputStream class.

  • void close(): Closes the stream
  • int write(byte[] b): Writes b.length bytes from the specified byte array to this file output stream.
  • int write(byte[] b, int off, int len): Writes len bytes from the specified byte array starting at offset off to this file output stream.
  • void write(int b): Writes the specified byte to this file output stream
Here is an example which writes data to a file data.txt with the help of various methods provided by the FileOutputStream class.

import java.io. * ;
class WriteData {
	public void write1(String data) throws IOException {
		/* write data using write(byte[] b) method */
		FileOutputStream fout = new FileOutputStream("data.txt");
		// Convert string to bytes    
		byte[] b = data.getBytes();
		// Write the byte array   
		fout.write(b);
		fout.close();
	}
	public void write2(String data) throws IOException {
		/*write data using write(int b) method*/
		FileOutputStream fout = new FileOutputStream("data.txt");
		// Convert string to char array 
		char[] c = data.toCharArray();
		for (int i = 0; i <c.length; i++) {
			fout.write(c[i]);
		}
		fout.close();
	}
	public void write3(String data) throws IOException {
		FileOutputStream fout = new FileOutputStream("data.txt");
		byte[] b1 = data.getBytes();
		fout.write(b1, 0, b1.length);
		fout.close();
	}
	public static void main(String args[]) throws Exception {
		String st = "This is going to be written on file.";
		/*any of the method can be called to write the data*/
		WriteData wd = new WriteData();
		Wd.write2(st);
	}
}

Reading a file using FileReader class

The FileReader class is the subclass of InputStreamReader which provides a character stream to read characters from the file.

List of Common methods of FileReader class.

  • void close() Closes the stream and release any associated resource.
  • int read() Reads a single character.
  • int read(char[] cbuf,int offset,int length) Reads characters into a portion of an array.
  • boolean ready() Tells whether this stream is ready to be read. An InputStreamReader is ready if its input buffer is not empty, or if bytes are available to be read from the underlying byte stream.
Example:

import java.io. * ;
class FileReaderExample {
	public static void main(String args[]) throws IOException {
		FileReader reader = new FileReader("data.txt");
		int ch;
		/*read each character from data.txt until end of the file reached*/
		while ((ch = reader.read()) != -1) {
			/*print each character*/
			System.out.println((char) ch);
		}
		reader.close();
	}
}

Writing to a file using FileWriter class

The FileWriter class is the subclass of OutputStreamWriter which provides a character stream to write characters to a file.

List of Common methods of FileWriter class.

  • void close(): Closes the stream and release any associated resource. Once a stream is closed further write operation would cause an IOException
  • void write(int c): Writes a single character.
  • void write(char[] cbuf,int off,int len) : Writes a portion of an array of characters.
  • void write(String str,int off,int len): Writes a portion of a string.
  • void flush(): Flushes the stream.
Example:

import java.io. * ;
class FileWriterExample {
	public static void main(String args[]) throws IOException {
		FileWriter writer = new FileWriter("data.txt");
		for (char c = 'A'; c < = 'Z'; c++) {
			writer.write(c);
			writer.flush();
		}
		writer.close();
	}
}

Serialization

Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.

After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.

Most impressive is that the entire process is JVM independent, meaning an object can be serialized on one platform and deserialized on an entirely different platform.

Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object.

The ObjectOutputStream class contains many write methods for writing various data types, but one method in particular stands out:


public final void writeObject(Object x) throws IOException 

The above method serializes an Object and sends it to the output stream. Similarly, the ObjectInputStream class contains the following method for deserializing an object:


public final Object readObject() throws IOException, ClassNotFoundException 

This method retrieves the next Object out of the stream and deserializes it. The return value is Object, so you will need to cast it to its appropriate data type.

To demonstrate how serialization works in Java, let us use create a class Employee which implements the Serializable interface.


public class Employee implements java.io.Serializable {
	public String name;
	public String address;
	public int number;
	public void display() {
		System.out.println("Hello, " + name);
	}
}

Notice that for a class to be serialized successfully, two conditions must be met:

  • The class must implement the java.io.Serializable interface.
  • All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient.

Serializing an Object

The ObjectOutputStream class is used to serialize an Object. The following SerializeDemo program instantiates an Employee object and serializes it to a file.

When the program is done executing, a file named employee.ser is created.


import java.io. * ;
public class SerializeDemo {
	public static void main(String[] args) {
		Employee e = new Employee();
		e.name = "John Anderson ";
		e.address = "72, park street";
		e.number = 101;
		try {
			FileOutputStream fileOut = new FileOutputStream("employee.ser");
			ObjectOutputStream out = new ObjectOutputStream(fileOut);
			out.writeObject(e);
			out.close();
			fileOut.close();
			System.out.printf("Serialized data is saved in employee.ser");
		}
		catch(IOException i) {
			i.printStackTrace();
		}
	}
}

Deserializing an Object

The following DeserializeDemo program deserializes the Employee object created in the SerializeDemo program.


import java.io. * ;
public class DeserializeDemo {
	public static void main(String[] args) {
		Employee e = null;
		try {
			FileInputStream fileIn = new FileInputStream("employee.ser");
			ObjectInputStream in =new ObjectInputStream(fileIn);
			e = (Employee) in .readObject(); in .close();
			fileIn.close();
		}
		catch(IOException i) {
			i.printStackTrace();
			return;
		}
		catch(ClassNotFoundException c) {
			System.out.println("Employee class not found
			c.printStackTrace();             
			return;        
		 }         
		System.out.println("
					Deserialized Employee...");         
		System.out.println("
					Name: " + e.name);         
		System.out.println("
					Address: " + e.address); 
		System.out.println("
					Number: " + e.number);      
	}
 } 
 
 

// Output:
Deserialized Employee… 
Name : John Anderson 
Address : 72, park street 
Number : 101 

About Author

Myself KarthiQ, I am the author of this blog, I know ways to write a good article but some how I donot have the skills to make it to reach people, would you like help me to reach more people By sharing this Article in the social media.

Share this Article Facebook
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions

Recent Addition

new tutorial Protractor Online Training : We have closed registration for training

Please do email to chercher.tech@gmail.com for any queries

If you already registered then please do check your email for the Webex link