Java IO: Input-Output in Java With Examples
Java IO: Input-Output in Java With Examples
Java brings various Streams with its I/O package that helps the user to perform all
the input-output operations. These streams support all the types of objects, data-
types, characters, files etc to fully execute the I/O operations.
Before exploring various input and output streams let’s look at 3 standard or
default streams that Java has to provide which are also most common in use:
Methods to write data on to the Console
System.out.print(parameter);
Example:
import java.io.*;
class Demo_print {
{
System.out.print("GfG! ");
System.out.print("GfG! ");
System.out.print("GfG! ");
}
}
Output:
System.out.println(parameter);
Example:
Import java.io.*;
class Demo_print {
{
System.out.println("GfG! ");
System.out.println("GfG! ");
System.out.println("GfG! ");
}
}
Output:
GfG!
GfG!
GfG!
Methods to Read Input from the Console
The input stream allows few methods using which we can read input data from
the console in Java.
The class BufferedReader was first introduced in JDK 1.0 and is the classical
method of reading input data from the console.
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;
BufferedReader reader =
}
}
Output:
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.
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.
{
}
}
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 following program reads the input data from the user using the scanner
class.
import java.util.Scanner;
class Main
{
}
}
Output:
In the above program, we have used the scanner class to read the string and
integer data.