You are here:   HomeJava ProgrammingStreamCreate a File and Write Data in Java Example
by Dinesh Thakur Category: Stream

Streams are represented in Java as classes. The java.io package defines a collection of stream classes that support input and output (reading and writing). To use these classes, a program needs to import the java.io package, as shown below

                       import java.io.* ; 

In general, streams are classified into two types known as character streams and the byte streams. The java.io package provides two sets of class hierarchies to handle character and byte streams for reading and writing:

l. Input Stream and Output Stream classes are operated on bytes for reading and  writing, respectively.

2. Classes Reader and Writer are operated on characters for reading and writing, respectively.

There are two other classes that are useful for handling input and output. These are File class and Random Access File class. A brief description of these four classes of java.io package.

Character streams

Reader and Writer are abstract super-classes for streaming l6-bit character inputs and outputs, respectively. Methods of these classes throw the IO Exception under error conditions.

All the methods in the Writer class have return type void.

                Description of the four classes in the package java.io.

Name of class

Description

Reader, Writer

Supports read/write 16-bit Unicode character. Used for only text data

Input Stream, Output stream

Define basic methods for input and output streams of data. these classes are used only for binary (byte) data.

.

File

Enables creating, deleting and renaming files, navigating through the file system, testing file existence and finding information about files.

Random Access File

Enables the program to read/write from/to any location in the file, not just the beginning/end of the file, is the case as in the usual sequential access. The file works as a random-access disk file.

           Reader class hierarchy classes in italic are of type

Reader class hierarchy classes in italic are of type (i) the rest are of type (ii).

             Writer class hierarchy classes

Writer class hierarchy classes shown in static are of type (i), the rest are of type (ii).

Character streams are normally divided into two types. (i) Those that only read from or on write on to streams and (ii) those that also process the data that was read/written. Figures and show the class hierarchies for the Reader and Writer classes.

The descriptions of Reader and Writer classes are summarized in Table

        Various Reader and Writer classes and their description

Class name

Description

Buffered Reader

Supports the buffering of the characters. It is a filter stream.

Buffered Writer

Increases the performance by buffering input/output.

Char Array Reader

Char Array Writer

Supports reading/writing of characters from/to a character array

Input Stream Reader

Output Stream Writer

Supports reading/writing of characters from/to a byte input stream

File Reader

File Writer

Supports reading/writing of characters from/to a file. These classes use default character encoding.

Filter Reader

Filter Writer

These two are abstract classes for characters Filter stream.

Piped Reader

Piped Writer

Supports the inter-thread communication. In pipe streams, the output from one method could be piped into the next one.

String Reader

String Writer

Reads/writes into the string. In String Reader the source for reading is String. String writer writes the output into the String Buffer. String Buffer is further converted into String.

Line Number Reader

Character input stream that keeps track of the line number

Push Back Reader

Allows one-character push back buffer for Reader. That is, after a character was read from reader, it is pushed back into the reader.

The example below illustrates how to read characters using the File Reader class.

            FileReader fr = new FileReader("filename.txt"); //Create a File Reader class from the file

                                                                                           filename.txt.

                      int i = fr.read();                                           //Read a character

Internally, to represent characters in computers, a character-encoding scheme (for example, ASCII) is generally used and every platform has a default character-encoding scheme. Java uses16-bit Unicode character-encoding scheme to represent characters internally. The Reader classes support conversions of Unicode characters to internal character storage. Besides using default encoding, Reader and Writer classes can also specify which encoding scheme to use. Most programs use Reader and Writer streams to read and write textual information. This is because they can handle any character in the Unicode character set. On the other hand, the byte streams are limited to ISO-Latin-l 8-bit bytes.

Byte streams

Byte streams are used in a program to read and write 8-bit bytes. Input Stream and Output Stream are the abstract super-classes of all byte streams that have a sequential nature. Input Stream and Output Stream provide the Application-Program Interface (API) and partial implementation for input streams (streams that read bytes) and output streams (streams that write bytes). These streams are typically used to read and write binary data such as those related to images and sounds. Methods of these two classes throw the IO Exception. All methods of the Output Stream will have the return type void. The hierarchies of Input Stream class and Output Stream class are shown in Figures and all the sub-classes of Input Stream and Output Stream work only on bytes. Note that both

       Input Stream class hierarchy

                                  Input Stream class hierarchy

       Output Stream class hierarchy

                                  Output Stream class hierarchy

Input Stream and Output Stream are inherited from the Object class. Since Input Stream and Output Stream are abstract classes, they cannot be used directly .A brief description of classes in the Input Stream' and Output Stream hierarchies are given in Table Two other classes that are available are Object input Stream and Object Output Stream, which are used for object serialization. These are the sub-classes of Input Stream and Output Stream which internally implement the Object input and Object Output interfaces, respectively. These classes are covered in section  We cover the most useful stream classes in the rest of this chapter.

Working with the I/O super-classes

The classes Reader and Input. Stream define similar APTs but for different data types. Reader contains the methods described in Table for reading characters and arrays of characters. Similarly, Input Stream defines the same methods but for reading bytes and arrays of bytes. These are listed in Table Both Reader and Input Stream provide methods for marking a location in the stream, skipping input and resetting the current position. The following code illustrates reading a character.

FilelnputStream inp = new FilelnputStream("filename.txt");

while ((input = inp.read()) != null)

{

        System.out.println(input);

}

Classes in the Input Stream and Output Stream hierarchies.

                                                          

Name of class

Description

File input Stream and

File Output Stream

Read/write data from/to a file on the native file system. These work only on bytes. File Output Stream allows creating a file if the file does not exist.

Filter input Stream and

Filter Output Stream

Abstract streams that are used to add new behaviors to existing stream classes. Used to read from or write to another stream. When a filter stream is created, it must be specified as to which stream it attaches to.

Piped input Steam and

Piped Output Stream

Used for inter-thread communications. These classes implement the input and output components of a pipe. Pipes are used to channel the output from one program (or thread) in to the input of another. A Piped input Stream must be connected to another Piped input Stream.

Byte Array input Stream and

Byte Array Output Stream

Read data from or write data to a byte array in memory.

Sequence input Stream

Concatenate multiple input streams into one input stream

String Buffer input Stream

Allow programs to read from a String Buffer as if it were an input stream.

Data input Stream and

Data Output Stream

Allows programs to read and write primitive Java data types such as int, long, Boolean and char in a machine-independent format.

Buffered input Stream and

Buffered Output Stream

Allows buffering of the data during reading or writing. These classes are used to buffer the data to speed up the reading and writing process. Buffering reduces the number of accesses required on the original data source and thus increasing the speed of the process.

Line Number input Stream

Input stream that keeps track of line numbers while reading.

Push back input Stream

Allows one-byte push back buffer for an input stream. That is, after a byte was read from an input stream, it is pushed back on to the input stream.

Print Stream

An output stream used to display the text. It allows the program to print the output in a fashion convenient to an output stream.

Methods contained by the Reader class, or reading character arrays.

Name of method

Description

int read( )

Returns the integer specifying the next available character in the input stream. Otherwise, it returns -1, that is, the end of the file.

int read(char cbuf[])

Allows reading up to the buffer and returns the number of characters read. Otherwise, returns -1.

int read(char cbuf[], int offset, int length)

Attempts to read number of characters specified by length from the offset. Otherwise, it returns -1.

            

Methods contained by the Input Stream class, for reaching arrays of bytes.

Name of Method

Description

int read( )

Returns integer specifying the next available byte in the input stream. Otherwise, it returns -I, that is the end of the file.

int read(char cbuf[ ])

Allows reading up to the buffer and returns the number of bytes read. Otherwise, it returns -1.

int read(char cbuf[ ], int offset, int length)

Attempts to read the number of bytes specified by length from the offset. Otherwise, it returns -1.

Similarly, Writer and Output Stream are parallel concepts. Like Reader and Input Stream, Writer (or Output Stream) defines the following methods for writing characters (or bytes) and arrays of characters (or arrays of bytes):

                            void write( int c )

                            void write( char cbuf[ ] )

                            void write( char cbuf[ ], int offset, int length)

These methods are used to write into the invoking stream. The first method writes a single character (or byte, in the case of Output Stream) to the invoking output stream. The second method writes the complete array into the invoking output stream. The final method writes the sub-range of the length of characters (or bytes, in the case of output stream) starting from the offset value of the buffer to the invoking stream. All of these stream classes, namely, Reader, Writer, Input Stream and Output Stream are automatically opened when they are created. A stream can be closed either implicitly or explicitly. When the stream object is no longer referenced, the garbage collector can implicitly close it. Alternatively, the close () method can be used to close the stream explicitly. In addition to read (), write () and close () methods, Table .lists some other methods that belong to Input Stream and Output Stream classes.

Other methods in Input Stream and Output Stream classes

Name of method

Description

Input Stream

    long skip(long n)

Skips n bytes in the input stream. It returns the number of bytes skipped

    Int  available ()

Returns the number of bytes still available in the input stream

    Synchronized void reset ()

Returns the file handler to the marked position that was previously set in the stream.

    Synchronized void mark(int n)

Marks a position in the stream that will be valid till the next n bytes are read.

    Boolean markSupported()

Returns true if the stream supports mark or reset, otherwise returns false.

Output Stream

     Void flush ()

Flushes any buffered output to be written





Subscribe To Free Daily Newsletter!

Get Free News Updates Delivered Directly To Your Inbox
About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to contact us.



What's New and Popular





Popular Article