0% found this document useful (0 votes)
130 views5 pages

Java Console Input and Output Methods

This document discusses various ways to perform console and file input/output operations in Java. There are three main ways to read console input: using BufferedReader, Scanner, or Console classes. BufferedReader wraps System.in in an InputStreamReader, Scanner also wraps System.in, and Console reads from the console if it is available. There are two main ways to write console output: using print() and println() methods of PrintStream, or the write() method. File I/O can be done with byte streams using FileInputStream and FileOutputStream, or character streams using FileReader and FileWriter.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
130 views5 pages

Java Console Input and Output Methods

This document discusses various ways to perform console and file input/output operations in Java. There are three main ways to read console input: using BufferedReader, Scanner, or Console classes. BufferedReader wraps System.in in an InputStreamReader, Scanner also wraps System.in, and Console reads from the console if it is available. There are two main ways to write console output: using print() and println() methods of PrintStream, or the write() method. File I/O can be done with byte streams using FileInputStream and FileOutputStream, or character streams using FileReader and FileWriter.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java Console Class:-

Console IO Operations in Java

Reading console input in java


In java, there are three ways to read console input. Using the 3 following ways, we can read input data from the console.

 Using BufferedReader class


 Using Scanner class
 Using Console class

1. Reading console input using BufferedReader class in java


Reading input data using the BufferedReader class is the traditional technique. This way of the reading method is used by wrapping
the [Link] (standard input stream) in an InputStreamReader which is wrapped in a BufferedReader, we can read input from the
console.
The BufferedReader class has defined in the [Link] package.

import [Link].*;
public class ReadingDemo {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader([Link]));
String name = "";
try {
[Link]("Please enter your name : ");
name = [Link]();
[Link]("Hello, " + name + "!");
}
catch(Exception e) {
[Link](e);
}
finally {
[Link]();
}
}
}

2. Reading console input using Scanner class in java


Reading input data using the Scanner class is the most commonly used method. This way of the reading method is used by wrapping
the [Link] (standard input stream) which is wrapped in a Scanner, we can read input from the console.
The Scanner class has defined in the [Link] package.

import [Link];
public class ReadingDemo {
public static void main(String[] args) {
Scanner in = new Scanner([Link]);
String name = "";
[Link]("Please enter your name : ");
name = [Link]();
[Link]("Hello, " + name + "!");

}
}

3. Reading console input using Console class in java


Reading input data using the Console class is the most commonly used method. This class was introduced in Java 1.6 version.
The Console class has defined in the [Link] package.

import [Link].*;

public class ReadingDemo {


public static void main(String[] args) {
String name;
Console con = [Link]();

if(con != null) {
name = [Link]("Please enter your name : ");
[Link]("Hello, " + name + "!!");
}
else {
[Link]("Console not available.");
}
}
}

Writing console output in java


In java, there are two methods to write console output. Using the 2 following methods, we can write output data to the console.

 Using print() and println() methods


 Using write() method

Let's explore the each method to write data with example.

1. Writing console output using print() and println() methods


The PrintStream is a bult-in class that provides two methods print() and println() to write console output. The print() and println() methods are
the most widely used methods for console output.
Both print() and println() methods are used with [Link] stream.

public class WritingDemo {


public static void main(String[] args) {
int[] list = new int[5];
for(int i = 0; i < 5; i++)
list[i] = i*10;
for(int i:list)
[Link](i); //prints in same line
[Link]("");
for(int i:list)
[Link](i); //Prints in separate lines
}}

2. Writing console output using write() method


Alternatively, the PrintStream class provides a method write() to write console output.
The write() method take integer as argument, and writes its ASCII equalent character on to the console, it also acept escape sequences.

public class WritingDemo {


public static void main(String[] args) {
int[] list = new int[26];
for(int i = 0; i < 26; i++) {
list[i] = i + 65;
}
for(int i:list) {
[Link](i);
[Link]('\n');
}
}
}

File Reading & Writing in Java


In java, there multiple ways to read data from a file and to write data to a file. The most commonly used
ways are as follows.

Using Byte Stream (FileInputStream and FileOutputStream)


Using Character Stream (FileReader and FileWriter)
Let's look each of these ways.

File Handling using Byte Stream


In java, we can use a byte stream to handle files. The byte stream has the following built-in classes to
perform various operations on a file.

FileInputStream - It is a built-in class in java that allows reading data from a file. This class has
implemented based on the byte stream. The FileInputStream class provides a method read() to read
data from a file byte by byte.
FileOutputStream - It is a built-in class in java that allows writing data to a file. This class has
implemented based on the byte stream. The FileOutputStream class provides a method write() to write
data to a file byte by byte.
Let's look at the following example program that reads data from a file and writes the same to another
file using FileInputStream and FileOutputStream classes.

Example
import [Link].*;
public class FileReadingTest {
public static void main(String args[]) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;

try {
in = new FileInputStream("C:\\OM\\[Link]");
out = new FileOutputStream("C:\\OM\\[Link]");

int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
[Link]("Reading and Writing has been success!!!");
}
catch(Exception e){
[Link](e);
}finally {
if (in != null) {
[Link]();
}
if (out != null) {
[Link]();
}
}
}
}

File Handling using Character Stream


In java, we can use a character stream to handle files. The character stream has the following built-in classes to perform various operations
on a file.

 FileReader - It is a built-in class in java that allows reading data from a file. This class has implemented based on the character
stream. The FileReader class provides a method read() to read data from a file character by character.
 FileWriter - It is a built-in class in java that allows writing data to a file. This class has implemented based on the character
stream. The FileWriter class provides a method write() to write data to a file character by character.

Let's look at the following example program that reads data from a file and writes the same to another file using FIleReader and FileWriter
classes.

import [Link].*;
public class FileIO {

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


FileReader in = null;
FileWriter out = null;

try {
in = new FileReader("C:\\OM\\[Link]");
out = new FileWriter("C:\\OM\\[Link]");
int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
[Link]("Reading and Writing in a file is done!!!");
}
catch(Exception e) {
[Link](e);
}
finally {
if (in != null) {
[Link]();
}
if (out != null) {
[Link]();
}
}
}
}

Common questions

Powered by AI

Finally blocks ensure that resources are closed regardless of exceptions during file I/O operations, which is crucial for preventing resource leaks that can lead to performance degradation. If streams are not properly closed, file handles may remain open, potentially exhausting the available resources, leading to application crashes or unpredictable behavior . Using finally ensures a measure of integrity in resource management, making applications more robust and reliable .

Byte streams, utilizing FileInputStream and FileOutputStream, are geared towards handling raw binary data, making them ideal for non-text files like images. They process one byte at a time, allowing precise control over input/output sequences, but require explicit handling of character encoding if reading or writing textual data. Character streams, using FileReader and FileWriter, are oriented towards character data with built-in support for handling encodings, making them better suited for reading and writing text files where character set compatibility is critical .

Character streams use Reader and Writer classes to handle data in 16-bit Unicode, offering automatic handling of encoding and decoding of character data, which simplifies working with text files across different character encodings. Byte streams, conversely, operate at the byte level without considering character encoding, which requires explicit management of character sets when processing text files, making it complex when dealing with internationalization or diverse text data . This difference is crucial for maintaining data integrity across diverse locales and character sets in text processing applications.

The methods print() and println() are generally more efficient for simple string outputs as they are more straightforward to use with strings. PrintStream's write() method, however, deals with bytes and is used when lower-level manipulation is needed or when dealing with ASCII conversion, which can introduce additional overhead in terms of processing and is less intuitive for direct string output operations without conversion .

Scanner and BufferedReader expose applications to potential security risks when handling sensitive data since they echo input to the console, which can display sensitive information like passwords. The lack of inherent encryption or secure handling of inputs could lead to data leaks if an application's input is logged or captured through console interception. Developers must implement additional checks or use specialized classes such as Console, which offers readPassword() for secure input handling to mitigate these risks .

FileOutputStream is designed for binary data, making it suitable for writing raw data like images or binary files because it handles byte streams and does not consider character encoding. FileWriter, optimized for character data, automatically handles encoding through character streams, simplifying text handling but without direct control over binary data. This distinction implies that developers must choose FileWriter for text to ensure proper encoding and use FileOutputStream when handling non-text data where character sets are irrelevant .

BufferedReader reads data from the input stream in a more traditional, blocking way and is generally more efficient for reading large. It requires wrapping in an InputStreamReader and usage of methods like readLine() to handle input, primarily as strings . Scanner, on the other hand, can parse the input more flexibly by offering methods like nextInt(), nextLine() etc., which can directly convert input into different data types. This makes Scanner more suitable for applications where type-specific input handling is required, albeit with potentially more overhead .

The Console class provides a more secure and straightforward API for console input operations, especially when dealing with password input, due to its readPassword() method which suppresses echoing of characters . However, it is not available in all environments, particularly when running applications from IDEs or without a physical console, which limits its applicability. The older methods, such as Scanner and BufferedReader, are more versatile as they do not rely on console availability, although they may be less secure when handling sensitive data due to echoing and lack of direct password support .

The Console class provides a more straightforward approach for error handling since it encapsulates the prompt-response interaction directly, and if the console is not available, it clearly provides a fallback mechanism with user notification. On the other hand, Scanner and BufferedReader both require more generic try-catch blocks to handle input/output exceptions as they deal directly with streams. These stream-handling classes do not inherently check for console availability but focus on exception management specific to I/O operations .

The Console class requires a genuine console environment to function effectively, meaning it is typically available when running an application from the command line with a direct console interface. Developers need to be aware that in environments like IDEs or GUI-based applications where a console may not be available, the Console class will fail, returning null. This limitation necessitates alternative input methods be implemented to ensure user input can be processed in non-console environments .

You might also like