0% found this document useful (0 votes)
15 views17 pages

Java Input and Output Streams Explained

The document provides an overview of input/output operations in Java, detailing the various streams available for handling data, including standard input/output streams (System.in, System.out, System.err) and their associated methods (print, println, printf). It explains the differences between byte streams and character streams, highlighting classes such as FileInputStream, FileOutputStream, FileReader, and FileWriter, along with examples of reading from and writing to files. Additionally, it discusses the benefits of using BufferedInputStream and BufferedOutputStream to enhance performance during I/O operations.

Uploaded by

middenchopra
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)
15 views17 pages

Java Input and Output Streams Explained

The document provides an overview of input/output operations in Java, detailing the various streams available for handling data, including standard input/output streams (System.in, System.out, System.err) and their associated methods (print, println, printf). It explains the differences between byte streams and character streams, highlighting classes such as FileInputStream, FileOutputStream, FileReader, and FileWriter, along with examples of reading from and writing to files. Additionally, it discusses the benefits of using BufferedInputStream and BufferedOutputStream to enhance performance during I/O operations.

Uploaded by

middenchopra
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

Input/output in Java

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 lets look at 3 standard or default streams that
Java has to provide which are also most common in use:

[Link]: This is the standard input stream that is used to read characters from the keyboard or
any other standard input device.

[Link]: This is the standard output stream that is used to produce the result of a program on
an output device like the computer screen.

Here is a list of the various print functions that we use to output statements:

print(): This method in Java is used to display a text on the console. This text is passed as the
parameter to this method in the form of String. This method prints the text on the console and the
cursor remains at the end of the text at the console. The next printing takes place from just here.

Syntax:

[Link](parameter);
Example:

// Java code to illustrate print()

Import [Link].*;

class Demo_print {

public static void main(String[] args)

// using print()

// all are printed in the

// same line

[Link]("GfG! ");

[Link]("GfG! ");

[Link]("GfG! ");

Output:

GfG! GfG! GfG!

println(): This method in Java is also used to display a text on the console. It prints the text on
the console and the cursor moves to the start of the next line at the console. The next printing
takes place from the next line.

Syntax:

[Link](parameter);

Example:

// Java code to illustrate println()


Import [Link].*;

class Demo_print {

public static void main(String[] args)

// using println()

// all are printed in the

// different line

[Link]("GfG! ");

[Link]("GfG! ");

[Link]("GfG! ");

Output:

GfG!

GfG!

GfG!

printf(): This is the easiest of all methods as this is similar to printf in C. Note that
[Link]() and [Link]() take a single argument, but printf() may take multiple
arguments. This is used to format the output in Java.

Example:

// A Java program to demonstrate working of printf() in Java

Class JavaFormatter1 {

Public static void main(String args[])


{

intx = 100;

[Link]( "Printing simple"+ " integer: x = %d\n", x);

// this will print it upto

// 2 decimal places

[Link]( "Formatted with" + " precision: PI = %.2f\n", [Link]);

floatn = 5.2f;

// automatically appends zero

// to the rightmost part of decimal

[Link]( "Formatted to " + "specific width: n = %.4f\n", n);

n = 2324435.3f;

// here number is formatted from

// right margin and occupies a

// width of 20 characters

[Link]("Formatted to "+ "right margin: n = %20.4f\n",n);

Output:

Printing simple integer: x = 100

Formatted with precision: PI = 3.14

Formatted to specific width: n = 5.2000

Formatted to right margin: n = 2324435.2500

[Link]: This is the standard error stream that is used to output all the error data that a
program might throw, on a computer screen or any standard output device.

This stream also uses all the 3 above-mentioned functions to output the error data:
print()

println()

printf()

Example:

// Java code to illustrate standard

// input output streams

Import [Link].*;

public class SimpleIO {

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

// Input Stream Reader class to read input

InputStreamReader inp = null;

// Storing the input in inp

inp = new InputStreamReader([Link]);

[Link]("Enter characters, "+ " and '0' to quit.");

charc;

do{

c = (char)[Link]();

[Link](c);

} while(c != '0');

Input:

GeeksforGeeks0
Output:

Enter characters, and '0' to quit.

G
e
e
k
s
f
o
r
G
e
e
k
s
0

Types of Streams:

Depending on the type of operations, streams can be divided into two primary classes:

Input Stream: These streams are used to read data that must be taken as an input from a source
array or file or any peripheral device. For eg., FileInputStream, BufferedInputStream,
ByteArrayInputStream etc.

Output Stream: These streams are used to write data as outputs into an array or file or any
output peripheral device. For eg., FileOutputStream, BufferedOutputStream,
ByteArrayOutputStream etc.

Depending on the types of file, Streams can be divided into two primary classes which can be
further divided into other classes as can be seen through the diagram below followed by the
explanations.

ByteStream: This is used to process data byte by byte (8 bits). Though it has many classes, the
FileInputStream and the FileOutputStream are the most popular ones. The FileInputStream is
used to read from the source and FileOutputStream is used to write to the destination. Here is the
list of various ByteStream Classes:
Stream class Description

BufferedInputStream It is used for Buffered Input Stream.

DataInputStream It contains method for reading java standard datatypes.

FileInputStream This is used to reads from a file

InputStream This is an abstract class that describes stream input.

PrintStream This contains the most used print() and println() method

BufferedOutputStream This is used for Buffered Output Stream.

DataOutputStream This contains method for writing java standard data types.

FileOutputStream This is used to write to a file.

OutputStream This is an abstract class that describe stream output.


1. Example:

// Java Program illustrating the

// Byte Stream to copy

// contents of one file to another file.

Import [Link].*;

public class BStream {

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

FileInputStream sourceStream = null;

FileOutputStream targetStream = null;

try{

sourceStream = new FileInputStream("[Link]");

targetStream = new FileOutputStream("[Link]");


// Reading source file and writing

// content to target file byte by byte

Int temp;

while(( temp = [Link]())!= -1)

[Link]((byte)temp);

finally{

if(sourceStream != null)

[Link]();

if(targetStream != null)

[Link]();

Output:

Shows contents of file [Link]

CharacterStream: In Java, characters are stored using Unicode conventions (Refer this for
details). Character stream automatically allows us to read/write data character by character.
Though it has many classes, the FileReader and the FileWriter are the most popular ones.
FileReader and FileWriter are character streams used to read from the source and write to the
destination respectively. Here is the list of various CharacterStream Classes:

Stream class Description

BufferedReader It is used to handle buffered input stream.

FileReader This is an input stream that reads from file.

InputStreamReader This input stream is used to translate byte to character.


Stream class Description

OutputStreamReader This output stream is used to translate character to byte.

Reader This is an abstract class that define character stream input.

PrintWriter This contains the most used print() and println() method

Writer This is an abstract class that define character stream output.

BufferedWriter This is used to handle buffered output stream.

FileWriter This is used to output stream that writes to file.

2. Example:

// Java Program illustrating that

// we can read a file in a human-readable

// format using FileReader

// Accessing FileReader, FileWriter,

// and IOException

Import [Link].*;

Public class GfG {

Public static void main(String[] args) throws IOException

FileReader sourceStream = null;

try{

sourceStream = new FileReader("[Link]");

// Reading sourcefile and

// writing content to target file

// character by character.
Int temp;

while((temp = [Link]())!= -1)

[Link]((char)temp);

finally{

// Closing stream as no longer in use

if(sourceStream != null)

[Link]();

Reading and Writing Files


A stream can be defined as a sequence of data. The InputStream is used to read data
from a source and the OutputStream is used for writing data to a destination.

Here is a hierarchy of classes to deal with Input and Output streams.


FileInputStream

This stream is used for reading data from the files. Objects can be created using the
keyword new and there are several types of constructors available.

Following constructor takes a file name as a string to create an input stream object to read
the file −

InputStream f = new FileInputStream("C:/java/hello");

Following constructor takes a file object to create an input stream object to read the file.
First we create a file object using File() method as follows −

File f = new File("C:/java/hello");


InputStream f = new FileInputStream(f);

Once you have InputStream object in hand, then there is a list of helper methods which can
be used to read to stream or to do other operations on the stream.

Sr.N
Method & Description
o.

public void close() throws IOException{}


1
This method closes the file output stream. Releases any system resources associated with the
file. Throws an IOException.
protected void finalize()throws IOException {}
2 This method cleans up the connection to the file. Ensures that the close method of this file
output stream is called when there are no more references to this stream. Throws an
IOException.
public int read(int r)throws IOException{}
3
This method reads the specified byte of data from the InputStream. Returns an int. Returns the
next byte of data and -1 will be returned if it's the end of the file.
public int read(byte[] r) throws IOException{}
4
This method reads [Link] bytes from the input stream into an array. Returns the total number
of bytes read. If it is the end of the file, -1 will be returned.

5 public int available() throws IOException{}


Gives the number of bytes that can be read from this file input stream. Returns an int.

There are other important input streams available, for more detail you can refer to the
following links −

 ByteArrayInputStream
 DataInputStream

FileOutputStream
FileOutputStream is used to create a file and write data into it. The stream would create a
file, if it doesn't already exist, before opening it for output.

Here are two constructors which can be used to create a FileOutputStream object.

Following constructor takes a file name as a string to create an input stream object to write
the file −

OutputStream f = new FileOutputStream("C:/java/hello")

Following constructor takes a file object to create an output stream object to write the file.
First, we create a file object using File() method as follows −

File f = new File("C:/java/hello");


OutputStream f = new FileOutputStream(f);

Once you have OutputStream object in hand, then there is a list of helper methods, which
can be used to write to stream or to do other operations on the stream.

Sr.N
Method & Description
o.

public void close() throws IOException{}


1
This method closes the file output stream. Releases any system resources associated with the
file. Throws an IOException.
protected void finalize()throws IOException {}
2 This method cleans up the connection to the file. Ensures that the close method of this file
output stream is called when there are no more references to this stream. Throws an
IOException.

3 public void write(int w)throws IOException{}


This methods writes the specified byte to the output stream.

4 public void write(byte[] w)


Writes [Link] bytes from the mentioned byte array to the OutputStream.

There are other important output streams available, for more detail you can refer to the
following links −

 ByteArrayOutputStream
 DataOutputStream
Example

Following is the example to demonstrate InputStream and OutputStream −

import [Link];

public class fileStreamTest {

public static void main(String args[]) {


try {
byte bWrite [] = {11,21,3,40,5};
OutputStream os = new FileOutputStream("[Link]");
for(int x = 0; x < [Link] ; x++) {
[Link]( bWrite[x] ); // writes the bytes
}
[Link]();

InputStream is = new FileInputStream("[Link]");


int size = [Link]();

for(int i = 0; i < size; i++) {


[Link]((char)[Link]() + " ");
}
[Link]();
} catch (IOException e) {
[Link]("Exception");
}
}
}

The above code would create file [Link] and would write given numbers in binary format.
Same would be the output on the stdout screen.

BufferedInputStream and BufferedOutputStream Classes in Java

BufferedInputStream and BufferedOutputStream are two classes in Java that are used to
improve the performance of input and output operations. They do this by buffering data,
which means that they store a small amount of data in memory before writing it to or
reading it from the underlying stream. This can improve performance because it reduces the
number of times that the underlying stream needs to be accessed.

BufferedInputStream and BufferedOutputStream can be used with any type of stream, but
they are especially useful for streams that are slow to access, such as network streams or
file streams.

BufferedInputStream and BufferedOutputStream are very useful classes for improving the
performance of input and output operations. They are easy to use and can be used with any
type of stream.

Here are some additional things to keep in mind when using BufferedInputStream and
BufferedOutputStream:

 BufferedInputStream and BufferedOutputStream are both AutoCloseable classes. This


means that they can be automatically closed using the try-with-resources statement.
 BufferedInputStream and BufferedOutputStream both have a default buffer size of
8192 bytes. However, you can specify a different buffer size when you create the
object.
 BufferedInputStream and BufferedOutputStream can be used to read and write data
from and to any stream, not just files.
Methods of BufferedInputStream Class
Method Description

Returns an estimate of the number of bytes that can be read (or


available() skipped over) from this input stream without blocking, which may
be 0, or 0 when end of stream is detected.

Closes this input stream and releases any system resources


close()
associated with this stream.

Marks the current position in this input stream. A subsequent


mark(int readlimit)
`reset()` will attempt to reposition the stream to this point.

Tells whether this input stream supports the `mark()` and


markSupported()
`reset()` methods.

read() Reads a byte of data from this input stream.

Reads up to `[Link]` bytes of data from this input stream into


read(byte[] b)
an array of bytes.

read(byte[] b, int off, Reads up to `len` bytes of data from this input stream into an
int len) array of bytes, starting at offset `off` in the array.

Repositions this stream to the position at which the last `mark()`


reset()
was set.

skip(long n) Skips over and discards `n` bytes of data from this input stream.

Methods of BufferedOutputStream Class


Method Description

Closes this output stream and releases any system resources


close()
associated with this stream.

Flushes this output stream and forces any buffered output bytes
flush()
to be written out to the underlying device.

write() Writes a byte to this output stream.

write(byte[] b) Writes `[Link]` bytes from the specified byte array to this
Method Description

output stream.

write(byte[] b, int off, Writes `len` bytes from the specified byte array starting at offset
int len) `off` to this output stream.

Code for Writing and Reading Data from the buffer using BufferedInputStream and
BufferedOutputStream

package practiceproject;
import [Link].*;
import [Link].*;
public class democlass {

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

File obj = new File("[Link]");


BufferedOutputStream bout = new BufferedOutputStream(new
FileOutputStream(obj));
[Link](2);
[Link]("file writing successful");
[Link]();
BufferedInputStream bin = new BufferedInputStream(new
FileInputStream(obj));
int data=[Link]();
[Link](data);
[Link]();
}
}
Copy

Code to read data from the buffer after skipping a byte using BufferedInputStream

package practiceproject;
import [Link].*;
import [Link].*;
public class democlass {

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

File obj = new File("[Link]");


BufferedInputStream bin = new BufferedInputStream(new
FileInputStream(obj));
int data=[Link]();
[Link](data);
[Link]([Link](1));
int data1=[Link]();
[Link]((char)data1);

}
}

Common questions

Powered by AI

In Java's I/O system, streams are categorized primarily into InputStream and OutputStream classes. InputStream is used for reading data from a source such as files or peripherals, using methods like read() that return byte data until the end of the stream is reached . Conversely, OutputStream is utilized for writing data to a destination, with methods like write() for outputting byte data . These classes serve as the foundation for handling byte-level data, with various specific implementations like FileInputStream, FileOutputStream, BufferedInputStream, and BufferedOutputStream offering more specialized functionalities .

To implement a Java program to copy file contents using ByteStream, you must employ FileInputStream for reading and FileOutputStream for writing. Open the input file as a FileInputStream and the output file as a FileOutputStream. Read bytes sequentially from the input stream using read() method, checking for end-of-file condition (indicated by returning -1), and write each byte onto the output stream using write() method . Ensure proper resource management with a finally block or try-with-resources to close streams, releasing system resources . Consider error handling to manage exceptions during reading or writing, such as IOException .

Character streams in Java are designed to handle character data, specifically utilizing Unicode, which is particularly beneficial for reading and writing text data . They automatically handle character encoding and decoding, which byte streams do not, as byte streams deal with raw binary data . An example scenario where character streams are preferable is when dealing with text files that contain multibyte characters or text that must be interpreted according to specific character encoding, such as UTF-8, where using FileReader or FileWriter would naturally handle the text encoding. This ensures that text elements such as new lines and specific characters are treated correctly .

The available() method in InputStream provides an estimate of the number of bytes that can be read without blocking, which helps manage efficient reads in I/O operations . Practically, in a Java program, you can use available() to determine how many bytes remain before the end-of-file, enabling informed decisions on buffer allocations or reading logic. For instance, before reading data into a buffer, calling inputstream.available() allows sizing the buffer optimally, potentially reducing the number of read operations required . This can improve performance in large file reads or network streams, though it should not be solely relied upon for precise byte counts because it's an estimate .

The read() method in InputStream reads the next byte of data from the input stream and returns an integer in the range from 0 to 255. If the end of the stream is reached, it returns -1 . This method is central to data consumption in input operations, as it translates byte data into integer format for further processing. Conversely, the write() method in OutputStream writes the specified byte to the output stream and accepts an integer that represents a single byte value . The roles of these methods are fundamental in stream operations, facilitating the transfer of data from sources into programs via InputStream, and from programs to destinations via OutputStream, upon converting and transmitting raw byte data .

BufferedInputStream and BufferedOutputStream enhance the performance of input and output operations by reducing the number of accesses to the underlying physical disk or network, which are typically slower than in-memory operations . They achieve this by maintaining an internal buffer—a section of memory where data is stored temporarily before being read or written, which minimizes direct stream reads and writes . This buffering reduces the frequency of I/O operations, leading to improved efficiency of data processing compared to using unbuffered streams like FileInputStream and FileOutputStream directly .

InputStreamReader acts as a bridge between byte streams and character streams in Java's I/O framework, enabling conversion of byte data into characters using a specified charset . This functionality is crucial for handling different character encodings because it allows the program to interpret the byte data correctly according to the desired charset, such as UTF-8 or ISO-8859-1, thereby ensuring text is read and represented accurately regardless of the original encoding . Its importance stems from the ability to handle internationalization effectively, reading byte data from diverse origins into consistent character formats .

When handling file operations in Java, it is crucial to manage resources efficiently by ensuring streams are closed to avoid resource leaks. This can be achieved using a finally block or Java's try-with-resources statement, which automatically handles closing resources . Error handling is equally important; exceptions such as FileNotFoundException and IOException should be caught and properly managed to ensure the application can handle file errors gracefully, potentially logging errors or informing users appropriately . Additionally, consider using Buffered streams for performance and understanding file pathing correctly to avoid errors due to incorrect paths .

The print() method in Java outputs the text as a String and keeps the cursor at the end of the output text, so subsequent outputs continue from there . The println() method behaves similarly but moves the cursor to the beginning of the next line after printing the output, which makes each output appear on a new line . The printf() method adds formatting capabilities similar to C's printf function and can take multiple arguments. It is used to format the output using format specifiers to control how variables are displayed, such as integer padding or decimal precision .

Java's try-with-resources statement simplifies resource management by ensuring that each resource is closed at the end of the statement, thus automatically handling cleanup operations. This mechanism not only makes code cleaner and more readable but also reduces the risk of resource leaks often encountered with traditional try-finally blocks, where developers might forget to close resources . This feature is particularly beneficial in I/O operations where streams are involved, as streams are prone to resource leaks if not properly closed. The try-with-resources statement guarantees each resource implements the AutoCloseable interface, ensuring they are automatically closed .

You might also like