0% found this document useful (0 votes)
17 views14 pages

Managing I/O Files in Java Programming

The document provides an overview of managing I/O files in Java, detailing the concept of streams, including byte and character streams, and their respective classes for reading and writing data. It explains standard input/output streams, methods for reading and writing files, and handling primitive data types. Additionally, it covers concatenating files and buffering operations using specific Java classes.

Uploaded by

scasshanmu
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)
17 views14 pages

Managing I/O Files in Java Programming

The document provides an overview of managing I/O files in Java, detailing the concept of streams, including byte and character streams, and their respective classes for reading and writing data. It explains standard input/output streams, methods for reading and writing files, and handling primitive data types. Additionally, it covers concatenating files and buffering operations using specific Java classes.

Uploaded by

scasshanmu
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

MUTHAYAMMAL COLLEGE OF ARTS & SCIENCE, RASIPURAM

DEPARTMENT OF COMPUTER APPLICATIONS

UNIT : V CLASS: I IT
PAPER NAME: JAVA PROGRAMMING PAPER CODE: 23M2UITC02
Managing I/O Files in Java: Introduction - Concept of stream - Stream classes -
Byte stream classes - Character stream classes - Using stream - Using the file class - Creation of
Files -Reading/Writing characters - Reading/Writing Bytes - Handling Primitive Data types –
Concatenating and buffering Bytes - Random access files.

MANAGING I/O FILES IN JAVA:

 The [Link] package contains nearly every class


you might ever need to perform input and output (I/O) in
Java.
 All these streams represent an input source and an output destination.
 The stream in the [Link] package supports many
data such as primitives, object, localized characters, etc.

Stream:

A stream can be defined as a sequence of


data.

In Java, 3 streams are created for us automatically. All these streams are attached with the console.

1) [Link]: standard output stream

2) [Link]: standard input stream

3) [Link]: standard error stream

Let's see the code to print output and an error message to the console.

[Link] ("simple message");


[Link] ("error message");

Let's see the code to get input from console.

1. int i =[Link](); //returns ASCII code of 1st character


2. [Link]((char)i); //will print the character
There are two kinds of Streams:

 Input Stream − The Input Stream is used to read data from a source.

 Output Stream − The Output Stream is used for writing data to a destination.

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
Input Stream and Output Stream.

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

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 method: 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 classes at the top of hierarchy.
They are Reader and Writer.

These two abstract classes have several concrete classes that handle unicode character.

Some important Character 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.

13
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.

int read() throws IOException


Below is a simple example explaining character input:
class CharRead
{
public static void main( String args[])
{
BufferedReader br = new Bufferedreader(new InputstreamReader([Link]));
char c = (char)[Link](); //Reading character
}
}

14
Reading Strings in Java:
To read string we have to use readLine () function with BufferedReader class's object.
String read Line () throws IOException
Program to take String input from Keyboard in Java:
import [Link].*;
class MyInput
{
public static void main(String[] args)
{
String text;
InputStreamReader isr = new InputStreamReader([Link]);
BufferedReader br = new BufferedReader(isr);
text = [Link](); //Reading String
[Link](text);
}
}

Standard Streams”

 All the programming languages provide support for standard I/O where the user's program
can take input from a keyboard and then produce an output on the computer screen.

 If you are aware of C or C++ programming languages, then you must be aware of three
standard devices STDIN, STDOUT and STDERR. Similarly.

 Java provides the following three standard streams:

 Standard Input − This is used to feed the data to user's program and usually a keyboard is
used as standard input stream and represented as System. in.

 Standard Output − this is used to output the data produced by the user's program and
usually a computer screen is used for standard output stream and represented as System. out.

 Standard Error − This is used to output the error data produced by the user's program and
usually a computer screen is used for standard error stream and represented as [Link].

Reading and Writing Files:

 As described earlier, a stream can be defined as a sequence of data.

 The Input Stream is used to read data from a source.

1
 The Output Stream is used for writing data to a destination.

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

The two important streams are File Input Stream and FileOutputStream, which would
be discussed in this tutorial.

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");


Input Stream f = new FileInputStream(f);

Once you have Input Stream 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.

1
[Link]. Method & Description

1
public void close() throws IOException{}

This method closes the file output stream. Releases any system resources associated with
the file. Throws an IOException.

2
protected void finalize()throws IOException {}

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 int read(int r)throws IOException{}

This method reads the specified byte of data from the Input Stream. Returns an int.
Returns the next byte of data and -1 will be returned if it's the end of the file.

4
public int read(byte[] r) throws IOException{}

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.

1
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.

[Link]. Method & Description

1
public void close() throws IOException{}

This method closes the file output stream. Releases any system resources associated
with the file. Throws an IOException.

2
protected void finalize()throws IOException {}

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 −

1
 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.

READING & WRITING BYTES IN JAVA:

1
Reading Bytes – classes:
 The basic class in [Link] to read data is [Link].

 All classes that read bytes are derived from this class.
This class is extended by the following classes. Detailed
examples follow later, but lets take a 10000 feet view of the
classes. We will look only at the most important classes.

 FileInputStream- This stream reads raw bytes from a file. The read methods in this class
return a byte of data read from a file.
 ObjectInputStream- This class is used to read objects written using ObjectOutputStream.
It deserializes the primitive data types and objects
 PipedInputStream- A Unix „pipe‟ like implementation can be accomplished using
this class. It can connect to a pipedoutputsteam and read data off it.
 BufferedInputStream- This is probably the most used class. It buffers the data from any
of the above input stream. The methods in this class increase reading efficiency since they try to
read the maximum number of bytes that can be read from the file system in one operation.
 ByteArrayInputStream-This class contains a buffer(array) or bytes that store the next few
bytes that will be read from the stream.

Writing Bytes – classes:


 All classes that write bytes extend [Link].

 The important classes are:

 FileOutputStream- The methods in this class write bytes of data to a file. Note that this
writes raw bytes and not characters.
 ObjectOutputStream – writes primitive java types and objects to an ouputstream. The
data could be written to a file or to a socket. Data written using this method can be read back using
the ObjectInputStream
 PipedOutputStream- A piped output stream connects to a PipedInputStream to read bytes.
Data may be written by one thread and read by another.
 BufferedOutputStream-It buffers data from an input stream and writes the buffered data.
It is an efficient method of writing data since the operating systems may write an array of bytes in
a single operation and invoking write operation for each byte may be inefficient

2
 PrintStream-It wraps an Input Stream and adds functionality to print various
representations of data values. It never throws IOException and there is an option for automatic
flushing
 ByteArrayOutputStream-This class writes bytes at an array of bytes.

Handling primitive data types:


The primitive types are also commonly referred to as simple types which can be put in four
groups:

 Integers: This group includes byte, short, int, and long, which are for whole-valued signed
numbers.

 Floating-point numbers: This group includes float and double, which represent numbers
with fractional precision.

 Characters: This group includes char, which represents symbols in a character set, like
letters and numbers.

 Boolean: This group includes boolean, which is a special type for representing true/false
values.

Concatenate & Buffer File in Java:


Concatenate:
It is possible to concatenate two or more files and save in a different file.
In java, by using SequenceInputStream class we can concatenate two or more files.

Buffer Files:
In java, we can create a buffer to store temporary data that is read from & written to a
stream and this process known as i/o buffer operation.
Buffer is sit between programmer and source/destination file.

Buffer can be created by using following classes:

 BufferedInputClass
 BufferedOutputClass
Example:
write a program to concatenate two file A & B and concatenated data print on output screen.
Import [Link].*;

2
public class FileConcat {
public static void main(String arg[]) throws IOException
{ FileInputStream I1 = null;
FileInputStream I2 = null;
I1 = new FileInputStream("[Link]"); //open file A for concatenate

I2 = new FileInputStream("[Link]"); //open file B for concatenate


// declare sis to store combined file
SequenceInputStream sis = null;
sis = new SequenceInputStream(I1, I2);
// create buffer for input output
BufferedInputStream ibs = new BufferedInputStream(sis);
BufferedOutputStream obs = new BufferedOutputStream([Link]);
int c;
while ((c = [Link]()) != -1) // read& write till the end of buffer
{
[Link]((char) c);
}
[Link]();
[Link]();
[Link]();
[Link]();
}
}

Suppose we have a File “[Link]”

Hello students I am aditya.

and File “[Link]”

Hello

2
Output: Hello students I am aditya.
Hello

Size Minimum Maximum


Category Types Precision Example
(bits) Value Value

byte 8 -128 127 From +127 to -128 byte b = 65;

char c = 'A';
char 16 0 216-1 All Unicode characters[1]
char c = 65;

short s =
short 16 -2 15 215-1 From +32,767 to -32,768
Integer 65;

From +2,147,483,647 to -
int 32 -231 231-1 int i = 65;
2,147,483,648

From
long l =
long 64 -2 63 263-1 +9,223,372,036,854,775,807 to
65L;
-9,223,372,036,854,775,808

(2-2- From 3.402,823,5 E+38 to float f =


float 32 2-149
23
)·2127 1.4 E-45 65f;
Floating-
point From
(2-2- double d =
double 64 2-1074 1.797,693,134,862,315,7 E+308
52
)·21023 65.55;
to 4.9 E-324

****************** UNIT V COMPLETED ******************

You might also like