Basic I/O Operations In Java (Input/Output Streams)

In this Video Tutorial, we will Discuss the Java Input-Output Mechanism such as Java User Input, InputStream, Java Printf, Println, etc. with Standard I/O Devices:

In every programming language, we need to have a mechanism to read input data and also send the processed data that is also known as Output to the end-user.

As you are aware, there are many input and output devices in the software world that programmers can use to read data from and write or output data to.

Read through our Complete Java training series to gain more insight into Java concepts.

Input Output Operations

Video Tutorial On Basic I/O Operations In Java

Using a Java program, you can read and write data from different sources and destinations. Reading and writing data sources and destinations include:

  • Files
  • Pipes
  • Network Connections
  • In-memory Buffers (E.g:  arrays)
  • System.in, System.out, System.error

In this video tutorial, we will have the input as a file and explore various classes, interfaces, and methods that are available to read data from the file.

Basic IO Operations In Java:

Java File Operations:

Java I/O (Input-Output) is a standard mechanism that processes the input and generates the output. The package “java.io” contains the methods to perform all the input and output operations.

To perform I/O operations faster, Java uses the concept of streams. A stream can be defined as a sequence of data consisting of bytes.

Let's learn more about Java I/O streams!!

Standard I/O Streams In Java

Java language offers access to system resources, standard input-output devices, etc. using a “System” class. This class implements a system-dependent programming interface to access various resources.

The System class belongs to the “java.lang” package of Java. Apart from providing standard I/O streams, System class also provides access to environment variables, external variables, loading files and libraries, and also a utility method arrayCopy for copying part of an array.

As this tutorial is based on standard I/O only, we will skip the rest of the facilities provided by the System class here.

From Input-Output point of view, the System class offers the following streams:

#1) Standard Input Stream (System.in)

The input stream provided by System class, System.in is used to read the input data from a standard input device like a keyboard.

The stream remains open and is ready to read the data supplied by the user to the standard input device.

The below example demonstrates the System.in.read function to read a single integer digit.

public class Main {
    public static void main(String args[]) throws java.io.IOException {
        int ch;
        System.out.println("Enter the character to be displayed : ");

       ch = System.in.read();
        System.out.println("You entered : " + (char)ch);
    
    }
}

Output:

standard input stream output

#2) Standard Output Stream (System.out)

The System.out interface of the System class is used to write the program output to the standard output device like the monitor. In most cases, the System.out interface writes the command output to the standard output device.

It uses three methods from the “PrintStream” class as the standard output derives from this class.

These methods are:

  1. print
  2. println
  3. write

The methods “print” and “println” have the same functionality except for a single difference that the println method appends a newline character (\n) to the output.

The write method is not used frequently except in cases where non-ASCII data is to be displayed.

The following example demonstrates the System.out stream.

public class Main {
    public static void main(String args[]) throws java.io.IOException {
       
        String stringType = "Java Tutorial Series";
        char[] charTypeArray = { 'a', 'e', 'i', 'o', 'u' };
        boolean booleanType = true;
        int integerType = 10;
        double doubleType = Math.PI;
        long longType = Long.MAX_VALUE;
        float floatType = Float.MIN_VALUE;
        
        System.out.println("String::" + stringType);
        System.out.print("Character::"); 
        System.out.println(charTypeArray);
        System.out.println("Boolean::" + booleanType);
        System.out.println("Integer::" + integerType);
        System.out.println("Double::" + doubleType);
        System.out.println("Long::" + longType);
        System.out.println("Float::" + floatType);
    }
}
 

Output:

standard output stream

The above program shows the “print” and “println” functions used with System.out interface. Here we have defined variables of different data types and display each of them using System.out interface.

#3) Standard Error Stream (System.err)

The standard error stream, System.err is used to display errors if any during the execution of the program.

Like System.out stream, the error stream also supports the three methods of PrintStream class, print, println and writes.

Methods To Read Input From The Console

Apart from the input stream described above, there are few more methods using which we can read input data from the console in Java.

These methods are discussed below.

#1) Class BufferedReader

The class BufferedReader was first introduced in JDK 1.0 and is the classical method of reading input data from the console.

The input stream (System.in) is wrapped inside the class InputStreamReader which is in turn wrapped in BufferedReader.

The following program shows the usage of the BufferedReader class to read input data from the user.

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
public class Main {
    public static void main(String[] args) throws IOException {
         
        BufferedReader reader =  
                   new BufferedReader(new InputStreamReader(System.in)); 
         
        System.out.println("Enter the input string");
        String name = reader.readLine(); 
  
        System.out.println("You entered: " + name);         
    } 
}
 

Output:

BufferReader output

In the above program, we have declared an object of BufferedReader class initialized to System.in stream. Using this object, we read an entire line of input.

As you can see, you can read the entire buffered data making this functionality very efficient. The only drawback is the cryptic code that might be hard to remember every time.

#2) Console Class

The class “System.console” can be used to read input from the console. This is used to especially read input characters like a password from the command line.

The method of reading input data using the console class is currently the most efficient and preferred method in Java.

The following program demonstrates the System.console class.

public class Main
{ 
    public static void main(String[] args)  
    {         
        System.out.println("Enter the input string");
        String name = System.console().readLine(); 
          
        System.out.println("You entered: " + name);         
    } 
}
 

Output:

Console class output

Using System.console class, you can read the input characters without echoing the characters. Hence this method is more useful for reading passwords. Secondly, you can also use format strings to format the input data, similar to the ones used in System.out.printf ().

Although this is the preferred way of reading input data, note that the class System.console cannot be used with an Interactive Java environment like IDEs.

#3) Scanner

Using a scanner class to read input data is probably the fastest and preferred method. The scanner is mostly used for parsing the data types including primitive types and strings. But it can also be used to read the input data and parse it using tokenized input.

The scanner class uses regular expressions for this purpose.

The following program reads the input data from the user using the scanner class.

import java.util.Scanner; 
  
class Main 
{ 
    public static void main(String args[]) 
    { 
        Scanner myscan = new Scanner(System.in); 
  
        System.out.println("Enter the input:");
        String mystr = myscan.nextLine(); 
        System.out.println("You entered a string:"+mystr); 
        System.out.println("Enter Next input:");  
        int num = myscan.nextInt();  
        System.out.println("You entered an integer:"+num); 
    } 
}
 

Output:

Scanner output

In the above program, we have used the scanner class to read the string and integer data.

Formatting Output In Java Using printf

We have already seen how to display the output in a Java program. In this section, we will see how to format this output. We make use of the printf function of the “PrintStream” class along with the “System.out” stream of Java for this purpose.

The printf function in Java is similar to the printf function in C/C++. Unlike System.out.print and System.out.println functions that take a single argument, System.out.printf takes more than one argument.

The following are the variations of the printf function in Java.

NoFunction prototypeDescription
1System.out.printf(string);Prints a string provided in the argument without any formatting
2System.out.printf(format, arguments);Prints the output using specified format string ‘format’ and arguments.
3System.out.printf(locale, format, arguments);Prints the output using specified format string by applying locale and the arguments.

Note that the function System.out.format () is the same as System.out.printf ().

The general syntax to specify the format string is as follows:

%<flags><width><.precision>specifier
<flags> => + for right-aligning, - for left-aligning.
<width><.precision> => to specify leading/trailing zeros and precision
<specifier> => suggests the data type.

For Example:

System.out.println(“ ‘%05.2f’%n”, 2.28);

Will generate the following output:

’02.28’

We will discuss printf in Java in detail in the later topics of this tutorial.

Frequently Asked Questions

Q #1) What are Standard Input and Standard Output?

Answer: Standard input and output streams are preconnected channels to communicate between the computer program and outside environment when the program begins its execution. The three different standards I/O streams are standard input (stdin), standard output (stdout), standard error (stderr).

Q #2) What is Standard Input in programming?

Answer: Standard input or stdin is the stream used to read input from a standard input device like a keyboard.

Q #3) What is the Input-Output stream?

Answer: An input-output stream represents a source that you read input from and the destination you direct your output to.

A stream, in general, represents many devices that are used as source and destinations namely, keyboard, disk file, monitors, etc.

Q #4) What is Standard input in Java?

Answer: The standard input in Java is provided by the System class as a System.in stream. The System class is a part of java.lang package.

Q #5) What is the Standard output in Java?

Answer: The standard output in Java is provided by System class as a System.out stream. The System class is a part of java.lang package.

Additional Examples – Input/Output Streams

Streams represent the flow of data and that data can be in any format (like byte, text, primitive data type, etc). To write data into a destination, the output stream is used and in order to read the data, the input stream is used.

Different Formats For Reading And Writing

Input/output can be read/write as the following different formats:

#1) Reading File As Byte Stream

Here the data will be read in byte format. “FileInputStream” and “FileOutputStream “classes are used for reading the content as a byte. In this way, for every byte, the compiler will send a request to the OS.

 import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class ByteStreamsDemo {

public static void main(String[] args) throws IOException {

FileInputStream fin =null;
FileOutputStream fout =null;

try {

fin=new FileInputStream("input.txt");
fout=new FileOutputStream("out.txt");

int c;

while((c=fin.read() )!= -1)

{

fout.write(c);

}

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

finally {

if(fin!=null) {

fin.close();

}if(fout!=null) {

fout.close();

}
}
}

} 

Reading file as Byte Streams1Reading file as Byte Streams2

#2) Reading File As Character Stream

In this way, the input stream will be read in character format. So, for each character, the compiler will send a request to the OS. “FileReader” and “FileWriter” classes are useful for reading the content as the character.

 public class CharStreamDemo {

public static void main(String[] args) throws IOException {

FileReader input = null;
FileWriter output = null;
try {

input = new FileReader("input.txt");

output = new FileWriter("out1.txt");

int c;

while ((c = input.read()) != -1) {

output.write(c);

}  } finally {

if (input != null) {

input.close();

}

if (output != null) {

output.close();

}
}
}
} 

Reading file as Character stream

#3) Buffering The Input/Output Stream

When you use the FileInputStream or FileReader classes, for every read or write operation, a new request will be sent to OS. So, this may lead to performance issues. In order to avoid this BufferedInputStream or BufferedReader, classes are used to wrap unbuffered classes.

This reads the input stream when the buffer is empty.

Likewise, FileOutputStream or FileWriter, classes are wrapped with BufferedOutputStream or BufferedWriter to write the output once the buffer is full.

 public class BufferedStreamDemo {

public static void main(String[] args) throws IOException
{

BufferedReader input = null;
BufferedWriter output = null;

try {
input = new BufferedReader(new FileReader("input.txt"));
output = new BufferedWriter(new FileWriter("out1.txt"));

int c;
while ((c = input.read()) != -1) {
output.write(c);
}
} finally {
if (input != null) {
input.close();
}
if (output != null) {
output.close();
}
}
}
} 

Buffering the input-output stream

#4) Reading As Data Stream

In this method, the DataInputStream or DataOutputStream, classes are used to read and write the content as primitive data types such as boolean, char, byte, short, int, long, float, double and String. Mostly the DataInputStream and DataOutputStream will be used together.

 public class DataInputOutputStreamDemo {
public static void main(String[] args) {
File file = new File("read.bin");

FileOutputStream fos = null;
DataOutputStream dos = null;
try {

fos=new FileOutputStream(file);
dos=new DataOutputStream(fos);
dos.writeInt(50244);
dos.writeDouble(400.253);
dos.writeChar('d');
dos.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {

if(fos!=null){
fos.close();
}
if(dos!=null){
dos.close();
}
} catch (Exception e) {

e.printStackTrace();
}
}

/*Reading operation */
FileInputStream fis = null;
DataInputStream dis = null;

try {

fis = new FileInputStream(file);
dis = new DataInputStream(fis);
System.out.println(dis.readInt());

System.out.println(dis.readDouble());
System.out.println(dis.readChar());
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(fis!=null){
fis.close();
}
if(dis!=null){
dis.close();
}
} catch (Exception e) {
e.printStackTrace();
}

}
}
} 

Reading as Data Streams1Reading as Data Streams2

#5) Reading As Object Stream

ObjectInputStream/ ObjectOutputStream, classes are useful to write objects in a file and read the objects from the file. For storing the object in a file, the class should implement the Serializable interface.

 public class ObjectStreamDemo implements Serializable {

int age ;
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
} } 

We are going to create an object for this “ObjectStreamDemo” class and we will write that object into a file and read the same object from that file.

 public class ObjectStreamDemoTest {

public static void main(String[] args) {
// TODO Auto-generated method stub

ObjectStreamDemo obj=new ObjectStreamDemo();

obj.setAge(32);
obj.setName("bob");
try {
FileOutputStream fos =
new FileOutputStream("t.tmp");
ObjectOutputStream oos = new
ObjectOutputStream(fos);
oos.writeObject(obj);
oos.close();

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

FileInputStream fis;
ObjectInputStream ois;
try {

fis = new FileInputStream("t.tmp");
ois = new ObjectInputStream(fis);
ObjectStreamDemo obj1
= (ObjectStreamDemo)ois.readObject();

System.out.println(obj1.name);
System.out.println(obj1.age);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block

e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

catch(Exception e) {
e.printStackTrace();

}
}
} 

ObjectStreamDemo1ObjectStreamDemo2

File I/O Operations

File class is useful for doing file operations.

Some of the file operations performed using File class include:

  1. Create a file
  2. Check if the file is existing
  3. Get the path of the file
  4. Write the file
  5. Read the file
  6. Delete a file and rename the file
  7. Check the file permissions and change the file permissions
  8. Move the file from one directory to another location

Demo Program to create, read, and write the file:

 public class CreateFileDemo {

public static void main(String[] args) throws IOException {

File newfile=new File("created.txt");

if(!newfile.exists()) {
newfile.createNewFile();

System.out.println("file not exist");

}

try {

String FILENAME="created.txt";
String content="hi how are u";

FileWriter fwt = new FileWriter(FILENAME);
BufferedWriter bwt = new BufferedWriter(fwt);

bwt.write(content);

System.out.println("writing completed ...");

bwt.close();

} catch (IOException e) {

e.printStackTrace();

}
}
} 

Demo Program to create, read and write the file

Key points to be noted:

  • A stream is a logical representation of the flow of data.
  • You can read/write data in a different format like byte, character, object, primitive data type.
  • File class is used to create a file, delete the file and Move or copy or rename the file.
  • BufferedInputStream or BufferedOutputStream is used to improve the performance by buffering the data.

Conclusion

Java has a java.lang package that provides the standard input and output facilities using the System class.

Apart from the streams, System.in and System.out that are used for standard input and output respectively, there are also other methods like BufferedReader, console class and scanner class that is used to read input from the user.

System.out stream uses “PrintStream” class function, print and println to display the output. These are the functions that are used to display the output without formatting. Another function “printf” which is similar to printf function in C/C++ is also used in Java for formatted output.

We will explore more on scanner class and printf function in Java in our upcoming tutorials.

=> Visit Here For The Exclusive Java Training Tutorial Series.

PREV Tutorial | NEXT Tutorial