0% found this document useful (0 votes)
19 views10 pages

Understanding Java IO Streams

Uploaded by

nikitaparmar9998
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)
19 views10 pages

Understanding Java IO Streams

Uploaded by

nikitaparmar9998
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

What is Java IO?

The [Link] package consists of input and output streams used to read and write data to files
or other input and output sources.

There are 3 categories of classes in [Link] package:

 Input Streams.
 Output Streams.
 Error Streams.

Java supports three streams that are automatically attached with the console.

1. [Link]: Standard output stream


2. [Link]: Standard input stream
3. [Link]: Standard error stream

Input Streams

As we know input source consists of data that needs to be read in order to extract information
from it. Input Streams help us to read data from the input source. It is an abstract class that
provides a programming interface for all input streams.

Input streams are opened implicitly as soon as it is created. To close the input stream, we use
a close() method on the source object.

Output Streams

The output of the executed program has to be stored in a file for further use. Output streams
help us to write data to a output source(may be file). Similarly like input streams output
streams are also abstract classes that provides a programming interface for all output streams.

The output stream is opened as soon as it is created and explicitly closed by using the close()
method.

Error Streams

Error streams are the same as output streams. In some ide’s error is displayed in different
colors (other than the color of output color). It gives output on the console the same as output
streams.

In day-to-day work, we do not enter the input into the programs manually. Also, the result of
the program needs to be stored somewhere for further use.

So, IO streams in Java provide us with input and output streams that help us to extract data
from the files and write the data into the files. Normally, we can create, delete, and edit files
using [Link].
In short, all the file manipulation is done using Java IO streams. Java IO streams also handle
user input functionality.

Types of Streams in Java


Depending on the types of operations, streams are divided into 2 primary classes.

Input Stream

It is an abstract superclass of the [Link] package and is used to read the data from an input
source. In other words, reading data from files or from a keyboard, etc. We can create an
object of the input stream class using the new keyword. The input stream class has several
types of constructors.

The following code takes the file name as a string, to read the data stored in the file.

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

InputStream Hierarchy
Useful methods of InputStream

1. public abstract int read() throws IOException

The method above helps to return the data of the next byte in the input stream. The value
returned is between 0 to 255. If no byte is read, the code returns -1, which indicates the end of
the file.

2. public int available() throws IOException

The method above returns the number of bytes that can be read from the input stream.

3. public void close() throws IOException


The method above closes the current input stream and releases any system resources
associated with it.

4. public void mark(int readlimit)

It marks the current position in the input stream. The readlimit argument tells the input stream
to read that many bytes to read before the mark position gets invalid.

5. public boolean markSupported()

It tells whether the mark() and reset() method is supported in a particular input stream. It
returns true if the mark and reset methods are supported by the particular input stream or else
return false.

6. public int read(byte[ ] b) throws IOException

The method above reads the bytes from the input stream and stores every byte in the buffer
array. It returns the total number of bytes stored in the buffer array. If there is no byte in
the input stream, it returns -1 as the stream is at the end of the file.

7. public int read(byte[ ] b , int off , len) throws IOException

It reads up to len bytes of data from the input stream. It returns the total number of bytes
stored in the buffer. Here the “off” is start offset in buffer array b where the data is written,
and the “len” represents the maximum number of bytes to read.

8. public void reset() throws IOException

It repositions the stream to the last called mark position. The reset method does nothing for
input stream class except throwing an exception.

9. public long skip(long n) throws IOException

This method discards n bytes of data from the input stream.

Examples

1. In the below example, we will use FileInputStream class to read the input file: [Link].

 Create a file [Link] and place it in the same directory as [Link]


 Let us suppose [Link] contains the following content:

Scaler Topics
From InterviewBit

Code:

import [Link].*;

class Main {
public static void main(String[] args) throws IOException {
try {
// loading a file into f variable
FileInputStream f = new FileInputStream("[Link]");

// initializing x to 0
int x = 0;
// while loop untill the end of the file.
while ((x = [Link]()) != -1) {
// printing the character
[Link]((char) x);
}
// closing a file
[Link]();
} catch (Exception e) {
// printing exception
[Link](e);
}
}
}

Output:

Scaler Topics
From InterviewBit

2. In the below example, we will use BufferedInputStream class to read the file.

Code:

import [Link].*;

class Main {

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


try {
// loading a file into f1 variable using FileInputStream
FileInputStream f1 = new FileInputStream("[Link]");

// loading a file into f2 variable using BufferInputStream


BufferedInputStream f2 = new BufferedInputStream(f1);

// using the available method


[Link]("Available bytes: " + [Link]());

int x = 0;
// while loop untill the end of the file.
while ((x = [Link]()) != -1) {
// printing the character
[Link]((char) x);
}
[Link]();
// closing a file
[Link]();
} catch (Exception e) {
// printing exception
[Link](e);
}
}
}

Output:

Available bytes: 31
Scaler Topics
From InterviewBit

3. In the below example we will use ByteArrayInputStream class to read the file.

Code:

import [Link].*;

class Main {

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


try {
// loading a file into f1 variable using FileInputStream
FileInputStream f1 = new FileInputStream("[Link]");

int x = 0;
String S = "";
// while loop untill the end of the file.
while ((x = [Link]()) != -1) {
// printing the character
S = S + (char) x;
}
// closing a input stream
[Link]();

// converting string to array of bytes


byte[] b = [Link]();
// declaring ByteArrayInputStream
ByteArrayInputStream b1 = new ByteArrayInputStream(b);

x = [Link]();
while (x != -1) {
[Link]((char) x);
x = [Link]();
}
[Link]();
// close the input stream
[Link]();
} catch (Exception e) {
// printing exception
[Link](e);
}
}
}

Output:

Scaler Topics
From InterviewBit

Output Stream
It is an abstract superclass of the [Link] package and writes data to an output resource. In
other words, writing the data into the files. We can create an object of the output stream class
using the new keyword. The output stream class has several types of constructors.

OutputStream Hierarchy

Useful methods of OutputStream

1. public void close() throws IOException

This method closes the current output stream and releases any system resources associated
with it. The closed stream cannot be reopened and operations cannot be performed within it.

2. public void flush() throws IOException


It flushes the current output stream and forces any buffered output to be written out.

3. Public void write(byte[ ] b) throws IOException

This method writes the [Link] bytes from the specified byte array to the output stream.

4. Public void write(byte[ ] b ,int off ,int len) throws IOException

It writes upto len bytes of data to the output stream. Here the “off” is the start offset in buffer
array b, and the “len” represents the maximum number of bytes to be written in the output
stream.

5. Public abstract void write(int b) throws IOException

The method above writes the specific bytes to the output stream. It does not return a value.

Some methods that are inherited from class [Link]. These methods are used for
both input stream and output stream purposes.

Example: clone, equals, finalise, getclass, hashCode, notify, notifyAll, toString, wait.

Examples

1. In the below example we will use FileOutputStream class to read the file.

Code:

import [Link].*;

class Main {

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


try {
// loading a file into f variable
FileOutputStream f = new FileOutputStream("[Link]");

String s = "Scaler Topics";


char arr[] = [Link]();
// initializing x to 0
int x = 0;
// while loop untill the end of the string.
while (x < [Link]()) {
// writing a byte into "[Link]" file
[Link](arr[x++]);
}
// closing a file
[Link]();
} catch (Exception e) {
// printing exception
[Link](e);
}
}
}
Output:

The [Link] file will contain the following text:

Scaler Topics

2. In the below example we will use BufferedOutputStream class to read the file.

Code:

import [Link].*;

class Main {

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


try {
// loading a file into f variable
FileOutputStream f1 = new FileOutputStream("[Link]");

// declaring a f1 as BufferedOutputStream
BufferedOutputStream f2 = new BufferedOutputStream(f1);

String s = "Scaler Topics";


char arr[] = [Link]();
// initializing x to 0
int x = 0;
// while loop untill the end of the string.
while (x < [Link]()) {
// writing a byte into "[Link]" file
[Link](arr[x++]);
}
// closing a file
[Link]();
[Link]();
} catch (Exception e) {
// printing exception
[Link](e);
}
}
}

Output:

The [Link] file will contain the following text:

Scaler Topics

3. In the below example we will use ByteArrayOutputStream class to read the file.

Code:

import [Link].*;

class Main {

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


try {
// loading a file into f variable
FileOutputStream f = new FileOutputStream("[Link]");

String s = "Scaler Topics";

// declaring ByteArrayOutputStream
ByteArrayOutputStream b1 = new ByteArrayOutputStream();

// writing a data to "[Link]" file


[Link]([Link]());
[Link](f);

// closing a file
[Link]();
} catch (Exception e) {
// printing exception
[Link](e);
}
}
}

Output:

The [Link]`` file will contain the following text:

Scaler Topics

Common questions

Powered by AI

When catching IO exceptions in Java, it's important to consider the nature of the problem, whether it's recoverable, and how it affects subsequent operations. Using try-catch blocks, exceptions can be caught and handled, such as by logging the error, informing users, or retrying operations. Effective error handling might involve wrapping IO code within utility functions to centralize exception logic or using try-with-resources to handle stream closures automatically. This minimizes resource leaks and ensures robust error management throughout I/O processes .

Java differentiates between byte input streams and character input streams in handling raw bytes versus sequences of characters. Byte streams, such as FileInputStream, operate on 8-bit bytes and are suitable for binary data, while character streams, such as FileReader, manage 16-bit Unicode characters, accommodating text in multiple languages. This distinction impacts file handling by determining whether data is processed as raw bytes or encoded text, affecting how programs handle text files versus binary files. When dealing with text, character streams are beneficial as they respect character encoding and inherently offer better internationalization support .

ByteArrayOutputStream and ByteArrayInputStream in Java provide an in-memory buffer as opposed to reading from or writing to a file. This allows for the manipulation of byte arrays directly in memory, which is faster and more flexible in situations where data doesn't need to persist on disk. These classes are useful for intermediate processing, such as compression or encryption operations, before writing the final output to a file. They also facilitate testing and mock input/output scenarios without the overhead of actual disk access .

Leaving input or output streams open in Java can lead to resource leaks by consuming system resources, such as memory and file handles, which are not reclaimed automatically. This can degrade performance and even cause the application to crash if resources are exhausted. The close() method is crucial as it releases these resources, ensuring that they are freed and available for other operations. It finalizes the stream operations and handles any pending flush in output streams to guarantee that data is completely written out .

In Java, output streams and error streams are both abstract classes used to write data to an output source, but they serve different purposes. Output streams are typically used for writing data to files or other output mediums and support flushing of buffers to ensure that data is properly written. Error streams, on the other hand, are used to write error messages or diagnostic information, often displaying them in a different color in IDEs to differentiate from standard output. They are automatically attached to the console and can also help in redirecting error messages for handling exceptions .

BufferedInputStream enhances file reading operations in Java by providing a buffer that temporarily stores bytes read from the underlying input stream. This buffering minimizes the number of I/O operations by reducing the frequency of read operations directly from the file, which can be slow due to disk access latency. Instead, the buffer is filled with a chunk of data, and subsequent read operations retrieve bytes from the buffer. This improves performance considerably in high-latency environments such as network streams .

The available() method in input stream classes is significant because it provides the number of remaining bytes that are available for reading without blocking. This information is useful in determining if there's more data to process and for controlling input buffer reading efficiently. For example, in the implementation using BufferedInputStream, calling the available() method allows for printing the number of bytes available in the stream before reading, helping in debugging and optimizing the stream operation .

The InputStream class in Java serves as the abstract superclass for all input streams, providing a programming interface for reading data from input sources such as files or keyboards. It includes various methods to read bytes from input streams, handle exceptions, close streams, and support marking positions. The class facilitates extracting information from different data sources by reading bytes sequentially until the end of the file or stream is reached .

The mark() and reset() methods in Java input streams are used for re-reading bytes from a previously marked position within the stream. The mark() method sets a read limit, which is the maximum number of bytes the stream can read before the mark position becomes invalid. The reset() method repositions the stream to the last marked position, allowing the program to reprocess data. This is especially useful in parsing operations where data may need to be reconsidered. However, not all streams support these methods, which necessitates checking the markSupported() method before using them .

The FileInputStream class is typically used for reading raw byte data from files and is ideal for scenarios involving binary data, such as images or audio files. However, its limitations include not handling character encoding, which makes it unsuitable for reading text files intended for international use. It also doesn't provide a buffer, meaning frequent direct file access can affect performance. For text files or when performance is a consideration, BufferedReader or BufferedInputStream may be more appropriate due to their character support and buffering capabilities .

You might also like