0% found this document useful (0 votes)
1 views29 pages

Unit-2 Input and Output Streams

The document provides an overview of input/output basics in Java, explaining the concept of streams, which are sequences of data linked to physical devices. It details the types of streams (input and output), predefined streams (System.in, System.out, System.err), and distinguishes between byte and character streams, including their respective classes and methods. Additionally, it emphasizes the use of BufferedReader for reading console input in a character-oriented manner.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views29 pages

Unit-2 Input and Output Streams

The document provides an overview of input/output basics in Java, explaining the concept of streams, which are sequences of data linked to physical devices. It details the types of streams (input and output), predefined streams (System.in, System.out, System.err), and distinguishes between byte and character streams, including their respective classes and methods. Additionally, it emphasizes the use of BufferedReader for reading console input in a character-oriented manner.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

IMS Engineering College

NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.


Tel: (0120) 4940000
Department: Computer Science and Engineering

INPUT/OUTPUT BASICS

Java programs perform I/O through streams.


A stream is linked to a physical device by the Java I/O system. All streams behave in the
same manner, even if the actual physical devices to which they are linked differ.
Thus, the same I/O classes and methods can be applied to different types of devices. This
means that an input stream can abstract many different kinds of input: from a disk file, a
keyboard, or a network socket.
Likewise, an output stream may refer to the console, a disk file, or a network connection.
Streams are a clean way to deal with input/ output without having every part of our code
understand the difference between a keyboard and a network, for example. Java
implements streams within class hierarchies defined in the java.io package
A stream can be defined as a sequence of data. The Input Stream is used to read data from a
source and the Output Stream is used for writing data to a destination.

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Stream in Java

Stream in Java represents sequential flow (or unbroken flow) of data from one place to
another place.
In other words, a stream is a path along which data flows (like a pipe along which water
flows).
It is required to accept data as input from the keyboard. The data in the form of stream may
be bytes, characters, objects, etc.

Predefined Streams

Java provides the following three standard streams –


A stream is always required if we want to move data from data source to data sink. For
example, a stream can carry data from:
• keyboard to memory
• memory to printer
• memory to a text file

The System class is defined in java.lang package. It contains three predefined stream vari-
ables: in, out, err. These are declared as public and static within the system.
• Standard Input − refers to the standard InputStream which is the keyboard by
default. This is used to feed the data to user’s program and represented as
System.in.

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

• Standard Output − refers to the standard OutputStream by default,this is console


and
represented as System.out.
• Standard Error − This is used to output the error data produced by the user’s
programand usually a computer screen is used for standard error stream and
representedas System.err.

System.out.println("simple message");
System.err.println("error message");
Code1:
int i=System.in.read();//returns ASCII code of 1st character
System.out.println((char)i);//will print the character

Types of Streams in Java

Basically, there are two types of streams in Java. They are as follows:
• Input stream
• Output stream

Input Stream:
A stream that receives or reads data from a data source and sends it to a Java program is
called input stream. Input represents the flow of data into a program.
Output Stream:
A stream that takes data from a Java program and sends or writes data to the destination
(data sink) is called output stream. A output represents the flow of data out of a program.
Output stream connects java program and a data sink. A Java program writes or sends data
to the data sink.

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Stream Classes in Java

Modern versions of Java platform define two types of I/O streams:


• Byte streams
• Character streams

Byte Streams in Java

Byte streams in Java are designed to provide a convenient way for handling the input and
output of bytes (i.e., units of 8-bits data). We use them for reading or writing to binary data
I/O.
Byte streams are especially used when we are working with binary files such as executable
files, image files, and files in low-level file formats such as .zip, .class, .obj, and .exe.
Binary files are those files that are machine readable. For example, a Java class file is an
extension of “.class” and humans cannot read it.
It can be processed by low-level tools such as a JVM (executable java.exe in Windows) and
java disassembler (executable javap.exe in Windows).
Another realtime example is storing a photo in a .bmp or .jpeg file. These files are certainly
not human readable. Photo editing or image manipulation software can only process them.
Byte streams that are used for reading are called input streams and for writing are
called output streams. They are represented by the abstract classes of InputStream and
OutputStream in Java.
Character Streams in Java
Character streams in Java are designed for handling the input and output of characters.
They use 16-bit Unicode characters.
Character streams are more efficient than byte streams. They are mainly used for reading or
writing to character or text-based I/O such as text files, text documents, XML, and HTML
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

files.
Text files are those files that are human readable. For example, a .txt file that contains
human-readable text. This file is created with a text editor such as Notepad in Windows.
Character streams that are used for reading are called readers and for writing are
called writers. They are represented by the abstract classes of Reader and Writer in Java

Stream Classes in Java

All streams in Java are represented by classes in java.io package. This package contains a
lot of stream classes that provide abilities for processing all types of data.
We can classify these stream classes into two basic groups based on the date type. They are
as follows:
• Byte Stream Classes (support for handling I/O operations based on bytes)
• Character Stream Classes (support for managing I/O operations on characters)

Byte Stream Classes


There are two kinds of byte stream classes in Java. They are as follows:
• InputStream classes
• OutputStream classes

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

InputStream class
InputStream class is an abstract class. It is the super class of all classes representing an
input stream of bytes.
• The Input Strearn class is the superclass for all byte-oriented input stream classes.
• All the methods of this class throw an IOException.
• Being an abstract class, the InputStrearn class cannot be instantiated hence,
itssubclasses are used

Some of the Input Stream classes are listed below

Class Description
Contains methods to read bytes from the buffer (memory area)
BufferedInputStream
Contains methods to read bytes from a byte array
ByteArrayInputStream
Contains methods to read Java primitive data types
DataInputStream
Contains methods to read bytes from a file
FileInputStream
Contains methods to read bytes from other input streams which it
FilterInputStream
uses as its basic source of data
Contains methods to read objects
ObjectInputStream
Contains methods to read from a piped output stream. Apipe input
Piped Input Stream
stream must be connected to a piped output stream
Contains methods to concatenate multiple input streams and then read
SequenceInputStream
from the combined stream

Fig. Input Stream class Hierarchy

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Some of the useful methods of InputStream are listed below

Method Description
public abstract int read() Reads the next byte of data from the input stream. It returns -1at
throws IOException the end of file.
public int available() Returns an estimate of the number of bytes that can be read
throws IOException from the current input stream.
public void close() Close the current input stream
throws IOException

Output Stream class


Output Stream class is an abstract class. It is the super class of all classes representing an
output stream of bytes. An output stream accepts output bytes and sends them to some sink.

Class Description
BufferedOutputStream Contains methods to write bytes into the buffer
ByteArrayOutputStream Contains methods to write bytes into a byte array
DataOutputStream Contains methods to write Java primitive data types
FileOutputStream Contains methods to write bytes to a file
FilterOutputStream Contains methods to write to other output streams
ObjectOutputStream Contains methods to write objects
PipedOutputStream Contains methods to write to a piped output stream
PrintStream Contains methods to print Java primitive data types

Some of the useful methods of OutputStream class are listed below.

Method Description
public void write(int)throws Write a byte to the current output stream.
IOException

public void write(byte[]) Write an array of byte to the current output


throws IOException
stream.
public void flush()throws Flushes the current output stream.
IOException

public void close()throws close the current output stream.


IOException

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Fig. OutputStream class Hierarchy

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

CharacterStream Classes in Java

Byte Stream classes in Java provide sufficient functionality to handle 1 byte (i.e. 8 bits) of any
type of I/O operation.
But it is incompatible to work directly with 16-bit Unicode characters.
To overcome this problem, Java platform added later CharacterStream classes to support for
characters.
CharacterStream classes were added in Java 1.1 version. It is not a part of language when it
was released in 1995.

Types of CharacterStream classes in Java

Like byte stream classes, character stream classes also contain two kinds of classes. They are
named as:
• Reader Stream classes
• Writer Stream classes

Some important Character stream reader classes are listed below.


Reader classes are used to read 16-bit unicode characters from the input stream.
• The Reader class is the superclass for all character-oriented input stream classes.
• All the methods of this class throw an IO Exception.
• Being an abstract class, the Reader class cannot be instantiated hence its subclasses
are used.

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Reader class Description


BufferedReader Contains methods to read characters from the buffer
FileReader Contains methods to read from a file
InputStreamReader Contains methods to convert bytes to characters
Reader Abstract class that describes character stream input
The Reader class defines various methods to perform reading operations on data of aninput
stream. Some of these methods are listed below.

Method Description
int read() returns the integral representation of the next available char-acter
of input. It returns -1 when end of file is encountered
int read (char buffer []) attempts to read buffer. length characters into the buffer and
returns the total number of characters successfully read. It re-turns
-I when end of file is encountered
int read (char buffer [], attempts to read ‘nChars’ characters into the buffer starting at
int loc, int nChars) buffer [loc] and returns the total number of characters suc-
cessfully read. It returns -1 when end of file is encountered
long skip (long nChars) skips ‘nChars’ characters of the input stream and returns the
number of actually skipped characters
void close () closes the input source. If an attempt is made to read even
after closing the stream then it generates IOException

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Some important Character stream writer classes are listed below.

Writer classes are used to write 16-bit Unicode characters onto an outputstream.
• The Writer class is the superclass for all character-oriented output stream classes .
• All the methods of this class throw an IOException.
• Being an abstract class, the Writer class cannot be instantiated hence, its subclasses
are used.

Writer class Description


BufferedWriter Contains methods to write characters to a buffer
FileWriter Contains methods to write to a file
OutputStreamReader Contains methods to convert from bytes to character
PrintWriter Output stream that contains print( ) and println( )
Writer Abstract class that describes character stream output
The Writer class defines various methods to perform writing operations on output stream.
Some of these methods are listed below.

Method Description
void write () writes data to the output stream
void write (int i) Writes a single character to the output stream
void write (char buffer [] ) writes an array of characters to the output stream
void write(char buffer [],int writes ‘n’ characters from the buffer starting atbuffer [loc]
loc, int nChars) to the output stream

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

void close () closes the output stream. If an attempt is made to perform


writing operation even after closing the stream then it
generates IOException
void flush () flushes the output stream and writes the waitingbuffered
output characters

READING CONSOLE INPUT


For commercial applications, the preferred method of reading console input is to use a
character-oriented stream. This makes your program easier to internationalize and maintain.
In Java, console input is accomplished by reading from System.in. To obtain a character-based
stream that is attached to the console, wrap System.in in a BufferedReader object.
Because System.in refers to an object of type InputStream, it can be used for inputStream.
Putting it all together, the following line of code creates a BufferedReader that is connected
to the keyboard:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
After this statement executes, br is a character-based stream that is linked to the console
through System.in.
Reading characters
The 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.
Syntax:
int read() throws IOException
Example:
Read character from keyboard import

java.io.*;
class Main
{
public static void main( String args[]) throws IOException

{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

char c;

System.out.println(“Enter characters, @ to quit”);

do

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

{
c = (char)br.read();

System.out.println(c);
}
while(c!=’@’);
}
}
Sample Output:
Enter characters, @ to quit
123@45
1
2
3
@

Example:
Read string from keyboard
The readLine() function with BufferedReader class’s object is used to read string from
keyboard.
Syntax:
String readLine() throws IOException
Example :
import java.io.*;
public class Main
{
public static void main(String args[])throws Exception
{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
System.out.println("Enter your name");
String name=br.readLine();
System.out.println("Welcome "+name);
}

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

}
Sample Output :
Enter your name
ims
Welcome ims

WRITING CONSOLE OUTPUT

• Console output is most easily accomplished with print( ) and println( ). These methods are
defined by the class PrintStream (which is the type of object referenced by System. out).
• Since PrintStream is an output stream derived from OutputStream, it also implements the
low-level method write( ).
• So, write( ) can be used to write to the console.

Syntax:
void write(int byteval)
This method writes to the stream the byte specified by byteval.
The following java program uses write( ) to output the character “A” followed by a new-line
to the screen:
// Demonstrate System.out.write().
class WriteDemo
{
public static void main(String args[])
{
int b;
b = ‘A’;

System.out.write(b);
System.out.write(‘\n’);
}
}
THE PRINTWRITER CLASS
• Although using System.out to write to the console is acceptable, its use is recommended
mostly for debugging purposes or for sample programs.
• For real-world programs, the recommended method of writing to the console when

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

using Java is through a PrintWriter stream.


• PrintWriter is one of the character-based classes.
• Using a character-based class for console output makes it easier to internationalize
our program.
• PrintWriter defines several constructors.
Syntax:
PrintWriter(OutputStream outputStream, boolean flushOnNewline)
Here,
• output Stream is an object of type OutputStream
• flushOnNewline controls whether Java flushes the output stream every time a println(
) method is called.
• If flushOnNewline is true, flushing automatically takes place. If false, flushing is not
automatic.
• PrintWriter supports the print( ) and println( ) methods for all types including
Object.
• Thus, we can use these methods in the same way as they have been used with System.
out.
• If an argument is not a simple type, the PrintWriter methods call the object’s toString(
) method and then print the result.
• To write to the console by using a PrintWriter, specify System.out for the output
stream and flush the stream after each newline.
For example, the following code creates a PrintWriter that is connected to console output:
PrintWriter pw = new PrintWriter(System.out, true);

The following application illustrates using a PrintWriter to handle console output:


// Demonstrate PrintWriter
import java.io.*;
public class Main2
{
public static void main(String args[])
{
PrintWriter pw = new PrintWriter(System.out, true);
pw.println("This is a string");
int i = -7;
pw.println(i);

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

double d = 4.5e7;
pw.println(d);
}
}
Sample Output:
This is a string
-7
4.5E7

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

READING AND WRITING FILES


In Java, all files are byte-oriented, and Java provides methods to read and write bytes fromand
to a file.
Two of the most often-used stream classes are FileInputStream and FileOutputStream,which
create byte streams linked to files.

File Input Stream


This stream is used for reading data from the files. Objects can be created using the key-word
new and there are several types of constructors available.
The two constructors which can be used to create a FileInputStream object:
i) Following constructor takes a file name as a string to create an input stream object to
read the file:
InputStream f = new FileInputStream(“filename “);

ii) 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);
Methods to read to stream or to do other operations on the stream.

Method Description
public void close() throws • Closes the file output stream.
IOException{} • Releases any system resources associated with the
file.
• Throws an IOException.

protected void • Ceans up the connection to the file.


finalize()throws IOException • 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 • Reads the specified byte of data from the InputStream.
IOException{} • Returns an int.
• Returns the next byte of data and -1 will be returned if it’s
the end of the file.

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

public int read(byte[] r) • Reads r.length bytes from the input stream into an
throws IOException{} array.
• Returns the total number of bytes read. If it is the end of the
file, -1 will be returned.
public int available() throws • Gives the number of bytes that can be read from this file
IOException{} input stream.
• Returns an int.

Steps to Read Data from File using FileInputStream class

There are the following steps to read data from a text file using FileInputStream that are
as follows:
1. First, we need to add a file to a FileInputStream as follows:

FileInputStream fis = new FileInputStream("myfile.txt");

This FileInputStream object enables us to read data from a file in the form of bytes.

2. Next step is to read data from a file. We need to call read() method using the file input
stream object reference variable. The syntax is as follows:

chars = fis.read();

Once the read() method reads all the characters from a file, it will reach the end of the file,
and -1 will be returned if there is no more data available to read further

Program code 1: Reading a single character


package javaProgram;
import java.io.FileInputStream;
public class ReadFile {
public static void main(String[] args)
{
try {
// Attach a file to FileInputStream for reading data and create an input stream for a file

FileInputStream fis = new FileInputStream("D:\\myfile.txt");

// Reading a value from a file in the form of byte.


int value = fis.read();
System.out.println("Reading a value in byte form: " +value);

// Converting byte into character to see text.


System.out.print((char)value); // Displaying a single character on console.
fis.close(); // Closing input stream automatically.

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

} catch(Exception e){
System.out.println(e);
}
}
}

Program code 2:

import java.io.FileInputStream;
public class ReadFile {
public static void main(String[] args)
{
try {
FileInputStream fis = new FileInputStream("D:\\myfile.txt");

// Reading all byte values from a file and display on the console.
int value = 0;
while((value = fis.read())!=-1)
{
System.out.print(value + " ");
}
fis.close();
} catch(Exception e) {
System.out.println(e);
}
}
}

Program code 3: Reading all characters from a file

import java.io.FileInputStream;
public class ReadFile {
public static void main(String[] args)
{
try {
FileInputStream fis = new FileInputStream("D:\\myfile.txt");

int value = 0;
while((value = fis.read())!=-1)
{
System.out.print((char)value);
}

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

fis.close();
} catch(Exception e){
System.out.println(e);
}
}
}

A program where we will see how to read a single byte, an array of bytes, and a subrange
array of bytes. We will also determine the number of available bytes remaining using
available() method and skip unwanted bytes by using skip() method.

Program code 4:
package javaProgram;
import java.io.FileInputStream;
import java.io.IOException;
public class ReadFile {
public static void main(String[ ] args) throws IOException
{
FileInputStream fis = new FileInputStream("D:\\myfile.txt");
int size = fis.available();

System.out.println("Total number of available bytes: " +size);


int n = size/10; // n = 2.

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


System.out.print((char) fis.read()); // Reading the first two characters W and e.
}
System.out.println("\nStill Available bytes: " + fis.available());
byte bytearray[ ] = new byte[2];

if (fis.read(bytearray) != n) {
System.out.println("Could not get" + n + "bytes");
}
String str = new String(bytearray, 0, n);
System.out.println(str);

System.out.println("\nStill available bytes: " +fis.available());


System.out.println("\nSkipping half of remaining bytes using skip() method");
fis.skip(size/2);

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

System.out.println("Still Available bytes: " + fis.available());

System.out.println("Reading " + n/2 + " from the end of array");


if (fis.read(bytearray, n/2, n/2) != n/2) {
System.out.println("couldn't read " + n/2 + " bytes.");
}
String str2 = new String(bytearray, 0, bytearray.length);
System.out.println(str2);

System.out.println("\nStill Available bytes: " + fis.available());


fis.close();
}
}
Output:
Total number of available bytes: 25
We
Still Available bytes: 23
lc

Still available bytes: 21

Skipping half of remaining bytes using skip() method


Still Available bytes: 9
Reading 1 from the end of array
lt
Still Available bytes: 8

File Output Stream


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.
The two constructors which can be used to create a FileOutputStream object:
i) Following constructor takes a file name as a string to create an input stream object to
write the file:
OutputStream f = new FileOutputStream(“filename”);

ii) 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

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

f = new FileOutputStream(f);
Methods to write to stream or to do other operations on the stream

Method Descriptio
n
public void close() throws • Closes the file output stream.
IO-Exception{} • Releases any system resources associated with
the
file.
• Throws an IOException.
protected void • Cleans up the connection to the file.
finalize()throws IOException • Ensures that the close method of this file output
{} stream is called when there are no more
referencesto this stream.
• Throws an IOException.
public void write(int • Writes the specified byte to the output stream.
w)throws IOException{}
public void write(byte[] w) • Writes w.length bytes from the mentioned byte
array to the OutputStream.

How to Create File using FileOutputStream

There are the following steps to create a text file that will store some characters or text. They
are:

1. First, we need to read data from the keyboard. For this purpose, we will have to attach
keyboard to an input stream class. The syntax for reading data from keyboard is given
below:
DataInputStream dis = new DataInputStream(System.in);
In the above statement, System.in represents the keyboard that is linked with
DataInputStream object whose reference variable is dis.
2. Second, attach a file where data is to be stored to an output stream. For this purpose, the
syntax for attaching a file fileout.txt to FileOutputStream is given below:

FileOutputStream fos = new FileOutputStream("fileout.txt");


Here, for represents object reference variable of FileOutputStream class.

3. Third step is to read data from DataInputStream and write it into FileOutputStream. This
means that we will read data from dis object and write it into fos object. The syntax is as
follows:

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

4. ch = (char)dis.read(); // Read a single character into ch.


fos.write(ch); // write ch into file.
At last, file must be closed after performing input or output operations on it. Otherwise, data
on the file may be corrupted. Look at the below figure to understand all these steps.

Program code 1:
package javaProgram;
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String[] args)
{
try {
// Store the filepath into the variable filepath of type String.
String filepath = "D:\\fileout.txt";

// Create an object of FileOutputStream class to attach file with FileOutputStream and pass
the filepath to its constructor.
FileOutputStream fos = new FileOutputStream(filepath);
fos.write(87);
fos.close(); // Closing file.

System.out.println("Successfully written");
}catch(FileNotFoundException e){
System.out.println(e);
}
}
}
Output:
Successfully written
Data “W” is successfully written into the text file fileout.txt.

Program code 2:
package javaProgram;
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String[] args)

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

{
try {
String filepath = "D:\\fileout.txt";
FileOutputStream fos = new FileOutputStream(filepath);
String str = "IMS Ghaziabd";

byte bytearray[ ] = str.getBytes(); // Converting string into byte array.


fos.write(bytearray);
fos.close();

System.out.println("Successfully written");
}catch(Exception e){
System.out.println(e);
}
}
}
Output:
Successfully written
Data “IMS Ghaziabad” is successfully written into the text file fileout.txt.

An example program where we will understand how to read data from the keyboard and
write it to fileout.txt file. Look at the program source code to understand better.
Program code 3:
package javaProgram;
import java.io.DataInputStream;
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String[] args)
{
try {
// Create an object of DataInputStream to attach keyboard to DataInputStream.
DataInputStream dis = new DataInputStream(System.in);

// Store the filepath into the variable filepath of type String.


String filepath = "D:\\myfileout.txt";

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

// Create an object of FileOutputStream to attach myfileout file to FileOutputStream.


FileOutputStream fos = new FileOutputStream(filepath);
System.out.println("Enter the text (@ at the end)");

int value = 0;
// Read the values (in byte form) from dis into ch and write them into fos.
while((value = dis.read()) != '@'){
char ch = (char)value; // Converting byte values into characters.
fos.write(ch);
}

fos.close(); // Closing file.


System.out.println("Successfully written...");
}catch(Exception e){
System.out.println(e);
}
}
}
Output:
Enter the text
Welcome to IMS Ghaziabad
@
Successfully written...

How to Copy Data from one File to another File?

Let’s create a program to copy data from one file to another file using FileInputStream
and FileOutputStream classes. In the first file myfile.txt, we will store data as “Welcome to
Scientech Easy”.
Then, we will copy it and store it in the second file myfileout.txt. Look at the source code to
understand better.
Program code 4:
package javaProgram;
import java.io.FileInputStream;

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

import java.io.FileOutputStream;
public class CopyData {
public static void main(String[] args)
{
try
{
FileInputStream fis = new FileInputStream("D:\\myfile.txt");
FileOutputStream fos = new FileOutputStream("D:\\myfileout.txt");

int i = 0;
while ((i = fis.read()) != -1){
char ch = (char)i;
fos.write(ch);
}
fis.close();
System.out.println("Successfully written...");
} catch(Exception e)
{
System.out.println(e);
}
}
}
Output:
Successfully written...

BufferedInputStream class
Java BufferedInputStream class is used to read information from stream. It internally uses
buffer mechanism to make the performance fast.
The BufferedInputStream class, a member of the java.io package, is an implementation of a
filtered input stream that provides buffering capabilities for other input streams.
Buffering can speed up I/O operations since it reduces the need to interact directly and
frequently with the source of the data.
The important points about BufferedInputStream are:
o When the bytes from the stream are skipped or read, the internal buffer automatically
refilled from the contained input stream, many bytes at a time.
o When a BufferedInputStream is created, an internal buffer array is created.

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

How it Works
By wrapping an existing input stream (like FileInputStream) with a BufferedInputStream, we can
read data from the buffer instead of the original source. This buffer gets refilled automatically when
it runs out of data, leading to fewer I/O operations and improved performance.

Java BufferedInputStream class declaration


Let's see the declaration for Java.io.BufferedInputStream class:
public class BufferedInputStream extends FilterInputStream

Program-1
import java.io.*;
public class BufferedInputStreamExample{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
BufferedInputStream bin=new BufferedInputStream(fin);
int i;
while((i=bin.read())!=-1){
System.out.print((char)i);
}
bin.close();
fin.close();
}catch(Exception e){System.out.println(e);}
}
}

Java BufferedOutputStream Class

The BufferedOutputStream class, found in the java.io package, is a filtered output stream that uses
an internal buffer to collect data before actually writing it to the underlying output stream. By
accumulating data in a buffer and then writing it in chunks, it helps reduce the I/O cost.
Java BufferedOutputStream class is used for buffering an output stream. It internally uses buffer to
store data. It adds more efficiency than to write data directly into a stream. So, it makes the
performance fast.

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

We can wrap an existing output stream (like FileOutputStream) with a BufferedOutputStream, we


can write data to the buffer. Once the buffer is full, the data is then flushed to the original output
stream in one go.
For adding the buffer in an OutputStream, use the BufferedOutputStream class.
Let's see the syntax for adding the buffer in an OutputStream:
OutputStream os= new BufferedOutputStream(new FileOutputStream("D:\\IO Package\\tes
tout.txt"));

Java BufferedOutputStream class declaration

Let's see the declaration for Java.io.BufferedOutputStream class:


public class BufferedOutputStream extends FilterOutputStream

import java.io.*;
public class BufferedOutputStreamExample{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
BufferedOutputStream bout=new BufferedOutputStream(fout);
String s="Welcome to javaTpoint.";
byte b[]=s.getBytes();
bout.write(b);
bout.flush();
bout.close();
fout.close();
System.out.println("success");
}
}

Java Input

Java provides different ways to get input from the user. Input from user using the object
of Scanner class. In order to use the object of Scanner, we need to import java.util.Scanner package.

import java.util.Scanner;
Then, we need to create an object of the Scanner class. We can use the object to take input from the
user.
// create an object of Scanner

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Scanner input = new Scanner(System.in);

// take input from the user


int number = input.nextInt();

import java.util.Scanner;

class Input
{
public static void main(String[] args)
{

Scanner input = new Scanner(System.in);

System.out.print("Enter an integer: ");


int number = input.nextInt();
System.out.println("You entered " + number);

// closing the scanner object


input.close();
}
}

We then call the nextInt() method of the Scanner class to get an integer input from the user.

Similarly, we can use nextLong(), nextFloat(), nextDouble(), and next() methods to


get long, float, double, and string input respectively from the user.

Note: We have used the close() method to close the object. It is recommended to close the scanner
object once the input is taken.

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE

You might also like