Input and Output Operations in Java

In this Java article we want to learn about Input and Output Operations in Java, Java is popular programming language that provides support for input and output operations. these operations allow you to interact with external resources such as files, networks and user input. in this article we want to talk about input and output operations in Java.

 

 

Input Operations

Input operations are used to receive data from an external source into the program. Java provides several classes and methods to read data from different sources, such as keyboard or a file.

 

Keyboard Input

Scanner class is commonly used to read input from the keyboard. this is an example of how to use the Scanner class to read user input, in this code snippet, we have created Scanner object that reads from standard input stream (System.in). after that we prompted the user to enter their name and read their input using the nextLine() method.

 

 

 

This will be the result

Input and Output Operations in Java
Input and Output Operations in Java

 

File Input

Java provides several classes to read data from files, such as FileInputStream and FileReader. this is an example of how to use the FileReader class to read a file:

In the above code we have used FileReader class to open file example.txt. after that we read the file character by character using read() method and print each character to the console.

 

 

This will be the result

Input and Output Operations in Java
Input and Output Operations in Java

 

 

Output Operations

Output operations are used to send data from the program to an external destination. Java provides several classes and methods to write data to different destinations, such as console or a file.

 

 

Console Output

System.out object is commonly used to write output to the console. this is an example of how to use System.out object to write output:

 

 

File Output

Java provides several classes to write data to files, such as FileOutputStream and FileWriter. this is an example of how to use the FileWriter class to write to a file:

In the above code we have used FileWriter class to open the file example.txt. after that we have used write() method to write a string  to the file.

 

 

Learn More

Leave a Comment