0% found this document useful (0 votes)
8 views16 pages

Java I/O Streams Overview and Examples

Uploaded by

ranganadh
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)
8 views16 pages

Java I/O Streams Overview and Examples

Uploaded by

ranganadh
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 IO Stream

Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O system to
make input and output operation in java. In general, a stream means continuous flow of data.
Streams are clean way to deal with input/output without having every part of your code
understand the physical.

Java encapsulates Stream under [Link] package. Java defines two types of streams. They are,

1. Byte Stream : It provides a convenient means for handling input and output of byte.

2. Character Stream : It provides a convenient means for handling input and output of
characters. Character stream uses Unicode and therefore can be internationalized.

Java Byte Stream Classes


Byte stream is defined by using two abstract class at the top of hierarchy, they are
InputStream and OutputStream.

These two abstract classes have several concrete classes that handle various devices such as
disk files, network connection etc.

Some important Byte stream classes.

Stream class Description

BufferedInputStream Used for Buffered Input Stream.

BufferedOutputStream Used for Buffered Output Stream.


DataInputStream Contains method for reading java standard datatype

DataOutputStream An output stream that contain method for writing java standard data type

FileInputStream Input stream that reads from a file

FileOutputStream Output stream that write to a file.

InputStream Abstract class that describe stream input.

OutputStream Abstract class that describe stream output.

PrintStream Output Stream that contain print() and println() method

These classes define several key methods. Two most important are

1. read() : reads byte of data.

2. write() : Writes byte of data.

Java Character Stream Classes


Character stream is also defined by using two abstract class at the top of hierarchy, they are
Reader and Writer.
These two abstract classes have several concrete classes that handle unicode character.

Some important Charcter stream classes

Stream class Description

BufferedReader Handles buffered input stream.

BufferedWriter Handles buffered output stream.

FileReader Input stream that reads from file.

FileWriter Output stream that writes to file.

InputStreamReader Input stream that translate byte to character

OutputStreamReader Output stream that translate character to byte.

PrintWriter Output Stream that contain print() and println() method.

Reader Abstract class that define character stream input

Writer Abstract class that define character stream output


Reading Console Input
We use the object of BufferedReader class to take inputs from the keyboard.

Reading Characters
read() method is used with BufferedReader object to read characters. As this function returns
integer type value has we need to use typecasting to convert it into char type.

Below is a simple example explaining character input.

// prg on reading a single character

import [Link].*;

class CharRead

public static void main( String args[])

throws Exception

{
BufferedReader br = new

BufferedReader(new InputStreamReader

([Link]));

[Link]("Enter Any

Character");

char c = (char)[Link](); //Reading

character

[Link]("The Given Char

"+c);

Reading Strings in Java


To read string we have to use readLine() function with BufferedReader class's object.

Program to take String input from Keyboard in Java

// Prg on reading string with


BufferedReader

import [Link].*;

class Testing

public static void main(String[] args)


throws Exception

String st;

BufferedReader x = new

BufferedReader(new InputStreamReader

([Link]));

[Link]("Enter Any String");

st = [Link](); //Reading String

[Link]("The Given String

"+st);

Program to read from a file using BufferedReader class

import java. Io *;

class ReadTest

public static void main(String[] args)

try

{
File fl = new File("d:/[Link]");

BufferedReader br = new BufferedReader(new FileReader(fl)) ;

String str;

while ((str=[Link]())!=null)

[Link](str);

[Link]();

[Link]();

catch(IOException e) {

[Link]();

Program to write to a File using FileWriter class

// Prg on writing to file

import [Link].*;

class WriteTest

public static void main(String[] args)

try
{

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

String str="All the best for the

Supplementary and Regular Exams";

FileWriter fw = new FileWriter(fl) ;

[Link](str);

[Link]();

[Link]("File Successfully

Created and Data was written into it");

catch (IOException e)

[Link]();

Java Serialization and Deserialization


Serialization is a process of converting an object into a sequence of bytes which can be
persisted to a disk or database or can be sent through streams. The reverse process of creating
object from sequence of bytes is called deserialization.

A class must implement Serializable interface present in [Link] package in order to serialize its
object successfully.

To implement serialization and deserialization, Java provides two classes ObjectOutputStream


and ObjectInputStream.
ObjectOutputStream class
It is used to write object states to the file. An object that implements [Link]
interface can be written to strams. It provides various methods to perform serialization.

ObjectInputStream class
An ObjectInputStream deserializes objects and primitive data written using an
ObjectOutputStream.

writeObject() and readObject() Methods


The writeObject() method of ObjectOutputStream class serializes an object and send it to the
output stream.

public final void writeObject(object x) throws IOException

The readObject() method of ObjectInputStream class references object out of stream and
deserialize it.

public final Object readObject() throws IOException,ClassNotFoundException

while serializing if you do not want any field to be part of object state then declare it
either static or transient based on your need and it will not be included during java serialization
process.

Example: Serializing an Object in Java


In this example, we have a class that implements Serializable interface to make its object
serialized.

import [Link].*;

class Studentinfo implements Serializable

String name;

int rid;

static String contact;

Studentinfo(String n, int r, String c)


{

[Link] = n;

[Link] = r;

[Link] = c;

class Demo

public static void main(String[] args)

try

Studentinfo si = new Studentinfo("Abhi", 104, "110044");

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

ObjectOutputStream oos = new ObjectOutputStream(fos);

[Link](si);

[Link]();

[Link]();

catch (Exception e)

[Link](e);

}
}

Object of Studentinfo class is serialized using writeObject() method and written


to [Link] file.

Example : Deserialization of Object in Java

To deserialize the object, we are using ObjectInputStream class that will read the object from
the specified file. See the below example.

import [Link].*;

class Studentinfo implements Serializable

String name;

int rid;

static String contact;

Studentinfo(String n, int r, String c)

[Link] = n;

[Link] = r;

[Link] = c;

class Demo

public static void main(String[] args)

Studentinfo si=null ;
try

FileInputStream fis = new FileInputStream("/filepath/[Link]");

ObjectInputStream ois = new ObjectInputStream(fis);

si = (Studentinfo)[Link]();

catch (Exception e)

[Link](); }

[Link]([Link]);

[Link]. println([Link]);

[Link]([Link]);

Output

Abhi

104

Null

transient Keyword
While serializing an object, if we don't want certain data member of the object to be serialized
we can mention it transient. transient keyword will prevent that data member from being
serialized.
class studentinfo implements Serializable

String name;

transient int rid;

static String contact;

 Making a data member transient will prevent its serialization.

 In this example rid will not be serialized because it is transient, and contact will also
remain unserialized because it is static.

RandomAccessFile
This class is used for reading and writing to random access file. A random access file behaves
like a large array of bytes. There is a cursor implied to the array called file pointer, by moving
the cursor we do the read write operations.

RandomAccessFile(File Creates a random access file stream to read from, and optionally to
file, String mode) write to, the file specified by the File argument.

Methods

Modifier Method Method


and Type
void close() It closes this random access file stream and releases
any system resources associated with the stream.

int readInt() It reads a signed 32-bit integer from this file.

void seek(long pos) It sets the file-pointer offset, measured from the
beginning of this file, at which the next read or write
occurs.

void writeDouble(double It converts the double argument to a long using the


v) doubleToLongBits method in class Double, and then
writes that long value to the file as an eight-byte
quantity, high byte first.

void writeFloat(float v) It converts the float argument to an int using the


floatToIntBits method in class Float, and then writes
that int value to the file as a four-byte quantity, high
byte first.

void write(int b) It writes the specified byte to this file.

int read() It reads a byte of data from this file.

long length() It returns the length of this file.

void seek(long pos) It sets the file-pointer offset, measured from the
beginning of this file, at which the next read or write
occurs.

Example

import [Link];

import [Link];
public class RandomAccessFileExample {

static final String FILEPATH ="[Link]";

public static void main(String[] args) {

try {

[Link](new String(readFromFile(FILEPATH, 0, 18)));

writeToFile(FILEPATH, "I love my country and my people", 31);

} catch (IOException e) {

[Link]();

private static byte[] readFromFile(String filePath, int position, int size)

throws IOException {

RandomAccessFile file = new RandomAccessFile(filePath, "r");

[Link](position);

byte[] bytes = new byte[size];

[Link](bytes);

[Link]();

return bytes;

private static void writeToFile(String filePath, String data, int position)

throws IOException {

RandomAccessFile file = new RandomAccessFile(filePath, "rw");

[Link](position);
[Link]([Link]());

[Link]();

The [Link] contains text "This class is used for reading and writing to random access file."

after running the program it will contains

I love my country and my people.

Common questions

Powered by AI

BufferedReader offers performance benefits due to its buffering capabilities, making it faster for reading lines of text compared to Scanner. Unlike Console, BufferedReader can be used in environments where the Console class might not work, such as IDEs. However, it requires more verbose exception handling (IOException) and lacks convenient methods for parsing data types directly, which Scanner provides out of the box .

Java implements serialization by converting objects into a byte stream through classes like ObjectOutputStream, and deserialization through ObjectInputStream. To serialize an object, it must implement the Serializable interface. Potential pitfalls include handling transient and static fields, which are not serialized. Developers must explicitly manage the exclusion of sensitive information with the transient keyword, and be aware that static fields are not serialized as they belong to the class, not the instance .

FileInputStream and FileOutputStream are used for reading and writing raw byte data, making them suitable for binary data such as images. In contrast, FileReader and FileWriter handle character data with automatic character encoding, ideal for text files. While byte streams are lower-level and do not account for character encoding, character streams simplify text processing and support internationalization. Each has limitations based on its data type handling, with performance trade-offs in encoding and buffering .

Proper closure of stream objects is crucial to release system resources, such as file handles, and to ensure that all data is flushed and written to the destination. Failure to close streams can lead to resource leaks, which may exhaust OS limits on open file descriptors. It can also result in data loss if the stream buffers are not flushed, and can affect the performance and reliability of applications .

Byte streams handle I/O of raw binary data, while character streams handle I/O of character data with Unicode support. Byte streams use InputStream and OutputStream classes and are ideal for binary data, such as image or audio files. In contrast, character streams use Reader and Writer classes and are suitable for text data, facilitating internationalization due to Unicode support .

Java's I/O system abstracts device-specific operations through the use of high-level stream classes such as InputStream and OutputStream for byte streams, and Reader and Writer for character streams. This abstraction hides the complexity of interacting directly with hardware, allowing developers to read from and write to different sources using a consistent API. This enhances code portability and scalability, freeing developers from managing communication details with various I/O devices .

The transient keyword in Java prevents the serialization of specific fields, allowing developers to exclude fields from the serialization process. This is useful for fields that do not make sense outside of the current JVM instance, such as file handles or threads. For example, declaring a field transient prevents it from being serialized, meaning its value will not be retained after deserialization. In the given example, the 'rid' field in 'Studentinfo' class is transient, and hence is not serialized, protecting sensitive or irrelevant data .

Data is read and written in Java using character streams through the abstract classes Reader and Writer. Concrete implementations include FileReader and FileWriter for file I/O, and BufferedReader and BufferedWriter for enhanced performance with buffering. These classes handle character data, supporting Unicode, making them suitable for text data manipulation, internationalization, and scenarios where encoding parameters are essential .

The seek() method allows setting the file-pointer to a specific location, enabling random access to data, rather than sequential. This feature is advantageous for applications that require partial file updates or data retrieval from specific offsets, like database implementations. The writeDouble() method is used to write double values directly, converting them into a long bit representation, facilitating the storage of floating-point numbers efficiently and with high precision, supporting complex data manipulations .

The RandomAccessFile class allows reading and writing to files at specific positions. It acts like an array of bytes with a pointer or cursor to move within the file, enabling non-sequential access. Primary use cases include scenarios where there is a need to manipulate files without processing the entire file sequentially, such as updating specific sections of a file or reading large files by loading portions into memory as needed .

You might also like