In java, I/O operations are performed through streams that are a flow of data that can be used for reading or writing. It performs the write and read operations in file permanently. Java, I/O streams, are also called File Handling, or File I/O that are available in java.io package. Reading and writing the data from different sources and destinations include Files, Network connections, Pipes, arrays, System.in, System.out, and System.err.

Streams link is established to a physical layer by a java I/O system to perform input and output operations. Streams are a continuous flow of data. The stream can support all data types, all types of objects, files, and characters to fully execute all input and output operations.

Java.io

Java.io package contains classes for system input and output through files, network streams, and memory buffers. Sometimes input and output streams are initialized automatically by JVM (java virtual machine) and these streams are available in system class.

System.in

System.in is a standard input stream that is used to read the characters from any peripheral device or source array or file. Most probably this input device is a keyboard. The input streams can be FileInputStream, BufferedInputStream, and ByteArrayInputStream etc.

System.out

System.out is an output stream that produces the result of any program into an array or peripheral device or file like a computer screen. Some output streams are FileOutputStream, BufferedOutputStream, and ByteArrayOutputStream etc.

System.err

System.err is a standard output stream that displays all error data that any program has on any output device.

Formatting output by using System.out

The following are the list of functions that System .out and System.err stream have;

  • print()
  • printf()
  • println()

print()

This method displays the text in the console. The text is passed as a parameter in the form of string. By using this method, the output is printed in the console, and the cursor remains at the end of output in the console window. The following output is a display from the end of the last output.

Syntax of print()

System.out.print(parameter);

Example of print() in Java

package print.function;
public class PrintFunction {
    public static void main(String[] args) {
        // this will print all the output in one line
        System.out.print("Java print method example ");
        System.out.print("Java print method example ");
        System.out.print("Java print method example ");
    }
}

Output

Java print method example Java print method example Java print method example

println()

This function also displays output in the console window. In this method, the output is printed and text is moved to the next line automatically. The next printing task takes place from the next line.

Example of PrintLn() in Java

package println.function;
public class PrintlnFunction {
    public static void main(String[] args) {
        System.out.println("Java println example ");
        System.out.println("Java println example ");
        System.out.println("Java println example ");
    }
}

Output

Java println example
Java println example
Java println example

printf()

This is the easiest and similar method to printf in the C language. prinf() method takes many arguments and is used to format output in java. The following variations are available in java of printf() function.

System.out.printf(string):  provide the string in the argument without any formatting.

System.out.printf(format, arguments): provide output by using the specified format that is provided as an argument.

System.out.printf(locale, format, arguments): deliver the output by using the specified format by applying locale and arguments.

Example

package prinf.function;
public class PrinfFunction {
    public static void main(String[] args) {
        int x = 100;
        //this will print simple integer
        System.out.printf("Printing value of simple " + "integrer : x = %d\n", x);
        //this will print upto 2 decimal places
        System.out.printf("Formatted with" + "precision: PI = %.2f\n", Math.PI);
        float n = 4.3 f;
        // this will automatically print zero to the rightmost part of decimal
        System.out.printf("Formatted according to " + "specific width: n = %.4f\n", n);
        n = 2324435.3 f;
        //here the number is formatted according to the right margin and will occupy the result of 20 characters
        System.out.printf("formated to" + "right margin: n = %20.4f\n", n);
    }
}

Output

Printing value of simple integer: x = 100
Formatted with precision: PI = 3.14
Formatted according to specific width: n=4.3000
Formatted to right margin: n=2324435.2500

Formatting output for System .err

This error stream also supports all the above functions that are supported by the output stream. These print functions are;

  • print()
  • println()
  • printf()

Example

package errorstream;
import java.io.*;
public class Errorstream {
    public static void main(String[] args) throws IOException {
        // inputstream reader class to read the inputs
        InputStreamReader num = null;
        //storing the input in num variable
        num = new InputStreamReader(System.in);
        System.out.println("Enter characters, " + "and '0' to quit. ");
        char c;
        do {
            c = (char) num.read();
            System.out.println(c);
        }
        while (c != '0');

    }

}

Input

FARKHANDA0

Output

F
A
R
K
H
A
N
D
A
0

Methods to read the input from the console

The following methods are available through the user can read the input data form the console window in java.

  • Class BufferedReader
  • Console Class
  • Scanner

Class BufferedReader

This class was first introduced in JDK 1.0 and provide the classical method of reading input from the console. The input stream class is wrapped in the class InputStreamReader that is then wrapped in BufferedReader.

Benefits

The input is buffered for reading efficiently and effectively.

Drawback

It’s tough to remember wrapping code.

Example:

package bufferreader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Bufferreader {
    public static void main(String[] args) throws IOException {
        // we declare an object of BufferedReader class and initialized it by using the System.in stream. By using this object we read entire input from the console.
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        // Take the input from a user

        System.out.println("Enter the input string");
        String name = reader.readLine();
        //print output in the console

        System.out.println("You entered: " + name);
    }
}

Output

Enter the input string

Farkhanda

You entered: Farkhanda

Console Class

This class is also used to input the data from the console class and is primarily used for reading input characters like passwords from the command line.

Benefits

  • It can read the password without echoing the characters that the user enters.
  • Reading methods are integrated.
  • A formatted string can also be used.

Drawback

  • Does not capable of working in non-interactive environments like IDE.

Example

public class Sample {
    public static void main(String[] args) {
        // Use Console to input data from user
        System.out.println("Enter the input string");
        String name = System.console().readLine();

        System.out.println("You entered: " + name);

    }
}

Output

Exception in thread “main” java.lang.NullPointerException
at bufferreader.Bufferreader.main(Bufferreader.java:14)

This method is preferred to read the input from the command line. This does not work in a non-interactive environment such as IDE and will throw an exception.

If you run this code in command line environment then the output will be;

Enter the input string

Java input and output operations

You entered: Java input and output operations.

Scanner

The scanner class is used for parsing the java data types that include primitive data types and strings. This can also be used for reading the input data and parse it by using the tokenized input.

Benefits

  • This is a convenient method for parsing primitive data types like nextInt(), nextFloat() from the tokenized input.
  • Regular expressions can also be used for finding the tokens.

Drawback

  • Synchronization cannot be performed by using reading methods.

Example

package bufferreader;
import java.util.Scanner;
public class Bufferreader {
    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

Enter the input:

JavaOperations

You entered a string: JavaOperations

Enter The Next input:

Different methods for reading and writing data from a file

Input and output can be read and write respectively by using the following formats;

  • Byte Stream
  • Character Stream

Byte stream

In this format, read and write operations are performed on data in byte format. This content can be characters, image data, and Unicode data that take 2 bytes to represent a character. For every byte, the compiler sends the request to the Operating System. Different classes are used for reading and writing the data under the java.io package;

Following are the classes that are used to read the byte data;

InputStream: This is an abstract class that is used to read byte streams.

FileInputStream: This class reads data in bytes from a file.

BufferedInputStream: This class provides wrapper functionalities over InputStream and is considered a more efficient method than FileInputStream.

The following are the classes used to write byte data:

OutputStream: An abstract class used to write the byte streams.

FileOutStream: This class writes raw bytes to a file.

ByteOutputStream: This class provides wrapper functionalities over OutputStream to support buffering capabilities. Again ByteOutputStream is considered a more efficient method than FileOutputStream due to buffering capabilities.

Character Stream

Character stream is used to read the data in character format. For each character, the compiler has to send a request to the Operating System. All the classes used for reading and writing character streams are located under the java.io package.

The following are the classes used for reading character data;

Reader: An abstract class that is used for reading a character stream.

InputStreamReader: This class reads the data in byte stream, then convert it into a character stream.

File Reader: This class is used to read the characters from a file.

BufferedReader: This is a wrapper class that provides wrapping capabilities over Reader class. This class is considered more efficient than others because it can read more data from the file in one class and reduce the number of I/O operations with a file.

Following are the classes used to write the character data;

Writer: An abstract that writes characters streams.

OutputStreamWriter: This class write character streams, then convert into byte streams.

FileWriter: The class that writes characters to the file.

BufferedWriter: This provides wrapper functionality over the Writer class that also supports buffering functionality. This class is preferred to write the data because it can write more data in one write() call.

Example of Reading and writing operations on text files.

The following examples will provide various methods of reading and writing text files using multiple classes. In the examples, read and write operations will be performed on a file located on the user’s home directory.

1- Read and Write operations with BufferedRedaer and BufferedWriter

String directory = System.getProperty("user.home");
String fileName = "sample.txt";
String absolutePath = directory + File.separator + fileName;
// Write the content in file
try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(absolutePath))) {
    String fileContent = "This is a sample text.";
    bufferedWriter.write(fileContent);
} catch (IOException e) {}
// Read the content from file
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(absolutePath))) {
    String line = bufferedReader.readLine();
    while (line != null) {
        System.out.println(line);
        line = bufferedReader.readLine();
    }
} catch (FileNotFoundException e) {
    // Exception handling
} catch (IOException e) {
    // Exception handling
}

2- Reading and writing operations with FileInputStream and FileOutputStream

String directory = System.getProperty("user.home");
String fileName = "sample.txt";
String absolutePath = directory + File.separator + fileName;
// write the content in file
try (FileOutputStream fileOutputStream = new FileOutputStream(absolutePath)) {
    String fileContent = "This is a sample text.";
    fileOutputStream.write(fileContent.getBytes());
} catch (FileNotFoundException e) {
    // exception handling
} catch (IOException e) {
    // exception handling
}
// reading the content of file
try (FileInputStream fileInputStream = new FileInputStream(absolutePath)) {
    int ch = fileInputStream.read();
    while (ch != -1) {
        System.out.print((char) ch);
        ch = fileInputStream.read();
    }
} catch (FileNotFoundException e) {
    // exception handling
} catch (IOException e) {
    // exception handling
}

3- Reading and writing with BufferedInputStream and BufferedOutputStream

String directory = System.getProperty("user.home");
String fileName = "sample.txt";
String absolutePath = directory + File.separator + fileName;
// write the content in file
try (BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(absolutePath))) {
    String fileContent = "This is a sample text.";
    bufferedOutputStream.write(fileContent.getBytes());
} catch (IOException e) {
    // exception handling
}
// read the content from file
try (BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(absolutePath))) {
    int ch = bufferedInputStream.read();
    while (ch != -1) {
        System.out.print((char) ch);
        ch = bufferedInputStream.read();
    }
} catch (FileNotFoundException e) {
    // exception handling
} catch (IOException e) {
    // exception handling
}

Conclusion

Java provides java.lang package that delivers facilities of standard input and standard output by using system classes. Apart from the streams, System.in and System .out classes are used for standard input and output functions. BufferedReader, console, and scanner classes are used for reading the input from users. Other than this I / O stream provide two streams for interacting with the files that are character streams and byte streams.

Last modified: October 10, 2020

Author

Comments

Write a Reply or Comment

Your email address will not be published.