Home | | Internet Programming | Java - I/O streaming

Chapter: Web or internet Programming : Java Programming

Java - I/O streaming

A stream is an abstraction that either produces or consumes information. A stream is linked to a physical device by the Java I/O system.

I/O streaming

 

       A stream is an abstraction that either produces or consumes information. A stream is linked to a physical device by the Java I/O system.

       Java 2 defines two types of streams: byte and character.

 

       Byte streams provide a convenient means for handling input and output of bytes. Byte streams are used, for example, when reading or writing binary data. two abstract classes are InputStream and OutputStream.

 

       Character streams provide a convenient means for handling input and output of characters. Two abstract classes are Reader and Writer. These abstract classes handle Unicode character streams.

       The package needed is java.io

 

Byte Streams

       The byte stream classes provide a rich environment for handling byte-oriented I/O.

 

       A byte stream can be used with any type of object, including binary data. This versatility makes byte streams important to many types of programs.

 

Input Streams

       Input streams read the bytes of data.

       Java's basic input class is java.io.InputStream

 

Methods

       public abstract int read( ) throws IOException

       public int read(byte[] input) throws IOException

       public int read(byte[] input, int offset, int length) throws IOException

 

       public long skip(long n) throws IOException

       public int available( ) throws IOException

       public void close( ) throws IOException

 

Output Streams

       Output streams write the bytes of data.

       Java's basic output class is java.io.OutputStream

 

Methods

       public abstract void write(int b) throws IOException

       public void write(byte[] data) throws IOException

       public void write(byte[] data, int offset, int length) throws IOException

       public void flush( ) throws IOException

       public void close( ) throws IOException

 

FileInputStream

   The FileInputStream class creates an InputStream that you can use to read bytes from a file.

 

       Its two constructors are

 

FileInputStream (String filepath) FileInputStream (File fileObj)

 

Either can throw a FileNotFoundException. The filepath is the full path name of a file, and fileObj is a File object that describes the file.

 

Example

 

import java.io.*; class FISDemo {

 

public static void main(String args[]) throws Exception { int size;

 

InputStream f = new FileInputStream("input.txt");

System.out.println("Total Available Bytes: " +(size = f.available())); int n = size;

 

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

System.out.print((char) f.read());

}

 

}

}

 

FileOutputStream

       FileOutputStream creates an OutputStream that you can use to write bytes to a file.

 

         Its constructors are

FileOutputStream (String filePath)

FileOutputStream (File fileObj)

Creation of a FileOutputStream is not dependent on the file already existing. FileOutputStream will create the file before opening it for output when you create the object. In the case where you attempt to open a read-only file, an IOException will be thrown.

Example

 

import java.io.*; class FOSDemo {

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

 

String source = "This is the program to demonstrate file output stream‖; byte buf[] = source.getBytes();

 

OutputStream f0 = new FileOutputStream ("file1.txt");

for (int i=0; i < buf.length; i += 2) {

f0.write (buf[i]);

}

 

f0.close ();

 

OutputStream f1 = new FileOutputStream ("file2.txt");

f1.write(buf);

f1.close();

 

}

 

}

 

ByteArrayInputStream

 

       ByteArrayInputStream is an implementation of an input stream that uses a byte array as the source.

 

       This class has two constructors, each of which requires a byte array to provide the data source ByteArrayInputStream(byte array[ ])

 

ByteArrayInputStream(byte array[ ], int start, int numBytes)

 

Example

 

import java.io.*; class BAISDemo {

 

public static void main(String args[]) throws IOException { String tmp = "abc";

byte b[] = tmp.getBytes();

 

ByteArrayInputStream in = new ByteArrayInputStream(b);

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

int c;

 

while ((c = in.read()) != -1) {

if (i == 0) {

System.out.print((char) c);

 

} else { System.out.print(Character.toUpperCase((char) c));

}

}

System.out.println();

 

in.reset();

}

 

}

}

 

 

       This example first reads each character from the stream and prints it as is, in lowercase. It then resets the stream and begins reading again, this time converting each character to uppercase before printing. The output is:

 

abc

ABC

 

ByteArrayOutputStream

 

       ByteArrayOutputStream is an implementation of an output stream that uses a byte array as the destination.

       ByteArrayOutputStream has two constructors

ByteArrayOutputStream( )

 

ByteArrayOutputStream(int numBytes)

 

       In the first constructor, a buffer of 32 bytes is created. In the second, a buffer is created with a size equal to that specified by numBytes.

 

 

Example import java.io.*;

class ByteArrayOutputStreamDemo {

 

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

ByteArrayOutputStream f = new ByteArrayOutputStream();

String s = "This should end up in the array";

 

byte buf[] = s.getBytes();

f.write(buf);

 

System.out.println("Buffer as a string");

System.out.println(f.toString());

System.out.println("Into array");

 

byte b[] = f.toByteArray();

for (int i=0; i<b.length; i++) {

System.out.print((char) b[i]);

}

 

System.out.println("\nTo an OutputStream()");

OutputStream f2 = new FileOutputStream ("test.txt");

f.writeTo(f2);

 

f2.close ();

System.out.println("Doing a reset"); f.reset();

 

for (int i=0; i<3; i++) f.write('X');

System.out.println(f.toString());

}

 

}

 

 

 

• When you run the program, you will create the following output. Notice how after the call to reset ( ), the three X’s end up at the beginning.

Buffer as a string

 

This should end up in the array Into array

 

This should end up in the array To an OutputStream ()

 

Doing a reset

XXX

 

Buffered Byte Streams

 

       For the byte-oriented streams, a buffered stream extends a filtered stream class by attaching a memory buffer to the I/O streams.

 

       This buffer allows Java to do I/O operations on more than a byte at a time, hence increasing performance. Because the buffer is available, skipping, marking, and resetting of the stream become possible.

 

       The buffered byte stream classes are BufferedInputStream and BufferedOutputStream. PushbackInputStream also implements a buffered stream.

 

Character Streams

 

       While the byte stream classes provide sufficient functionality to handle any type of I/O operation, they cannot work directly with Unicode characters.

 

       Since one of the main purposes of Java is to support the ―write once, run anywhere‖ philosophy, it was necessary to include direct I/O support for characters.

 

Reader

       Reader is an abstract class that defines Java‘s model of streaming character input.

 

Methods

       abstract void close( ) Closes the input source. Further read attempts will generate an IOException.

 

       void mark(int numChars) Places a mark at the current point in the input stream that will remain valid until numChars characters are read.

       boolean markSupported( ) Returns true if mark( )/reset( ) are supported on this stream.

 

       int read( ) Returns an integer representation of the next available character from the invoking input stream. –1 is returned when the end of the file is encountered.

 

       int read(char buffer[ ]) Attempts to read up to buffer.length characters into buffer and returns the actual number of characters that were successfully read. –1 is returned when the end of the file is encountered.

 

       abstract int read(char buffer[ ], int offset, int numChars) Attempts to read up to numChars characters into buffer starting at buffer[offset], returning the number of characters successfully read. –1 is returned when the end of the file is encountered.

       boolean ready( ) Returns true if the next input request will not wait. Otherwise, it returns false.

       void reset( ) Resets the input pointer to the previously set mark.

       long skip(long numChars) Skips over numChars characters of input, returning the number of characters actually skipped.

 

Writer

       Writer is an abstract class that defines streaming character output.

 

Methods

 

       abstract void close ( ) Closes the output stream. Further write attempts will generate an IOException.

 

       abstract void flush ( ) Finalizes the output state so that any buffers are cleared. That is, it flushes the output buffers.

 

       void write(int ch) Writes a single character to the invoking output stream. Note that the parameter is an int, which allows you to call write with expressions without having to cast them back to char.

 

       void write(char buffer[ ]) Writes a complete array of characters to the invoking output stream.

 

       abstract void write(char buffer[ ], int offset, int numChars) Writes a subrange of numChars characters from the array buffer, beginning at buffer[offset] to the invoking output stream.

       void write(String str) Writes str to the invoking output stream.

 

       void write(String str, int offset, int numChars) Writes a subrange of numChars characters from the array str, beginning at the specified offset.

 

 

FileReader

       The FileReader class creates a Reader that you can use to read the contents of a file.

         Its constructors are

FileReader (String filePath)

FileReader (File fileObj)

 

       Either can throw a FileNotFoundException. Here, filePath is the full path name of a file, and fileObj is a File object that describes the file.

 

Example import java.io.*;

class FileReaderDemo {

 

public static void main(String args[]) throws Exception { FileReader fr = new FileReader("FileReaderDemo.java"); BufferedReader br = new BufferedReader(fr);

String s;

 

while((s = br.readLine()) != null) { System.out.println(s);

}

fr.close();

 

}

}

 

FileWriter

FileWriter creates a Writer that you can use to write to a file.

• Its constructors are FileWriter(String filePath) FileWriter (String filePath, boolean append) FileWriter (File fileObj) FileWriter (File fileObj, boolean append)

 

       They can throw an IOException. Here, filePath is the full path name of a file, and fileObj is a File object that describes the file. If append is true, then output is appended to the end of the file.

 

Example import java.io.*;

 

class FileWriterDemo {

 

public static void main(String args[]) throws Exception { String source = "Now is the time for all good men\n"

 

+  " to come to the aid of their country\n"

+  " and pay their due taxes.";

 

char buffer[] = new char[source.length()];

source.getChars(0, source.length(), buffer, 0);

FileWriter f0 = new FileWriter("file1.txt");

for (int i=0; i < buffer.length; i += 2) {

 

f0.write(buffer[i]);

}

 

f0.close();

 

FileWriter f1 = new FileWriter("file2.txt");

f1.write(buffer); f1.close();

 

FileWriter f2 = new FileWriter("file3.txt");

f2.write(buffer,buffer.length-buffer.length/4,buffer.length/4);

f2.close();

}

}

 

       This example creates a sample buffer of characters by first making a String and then using the getChars( ) method to extract the character array equivalent. It then creates three files.

 

       The first, file1.txt, will contain every other character from the sample. The second, file2.txt, will contain the entire set of characters. Finally, the third, file3.txt, will contain only the last quarter.

 

CharArrayReader

 

       CharArrayReader is an implementation of an input stream that uses a character array as the source.

 

       This class has two constructors, each of which requires a character array to provide the data source:

CharArrayReader (char array [ ])

CharArrayReader (char array [ ], int start, int numChars)

 

Here, array is the input source. The second constructor creates a Reader from a subset of your character array that begins with the character at the index specified by start and is numChars long.

Example import java.io.*;

 

public class CharArrayReaderDemo {

 

public static void main(String args[]) throws IOException { String tmp = "abcdefghijklmnopqrstuvwxyz";

 

int length = tmp.length(); char c[] = new char[length]; tmp.getChars(0, length, c, 0);

 

CharArrayReader input1 = new CharArrayReader(c); CharArrayReader input2 = new CharArrayReader(c, 0, 5); int i;

 

System.out.println("input1 is:"); while((i = input1.read()) != -1) { System.out.print((char)i);

 

}

 

System.out.println(); System.out.println("input2 is:"); while((i = input2.read()) != -1) {

 

System.out.print((char)i);

}

 

System.out.println();

}

 

}

 

       The input1 object is constructed using the entire lowercase alphabet, while input2 contains only the first five letters. Here is the output:

 

input1 is: abcdefghijklmnopqrstuvwxyz input2 is:

abcde

 

CharArrayWriter

       CharArrayWriter is an implementation of an output stream that uses an array as the destination.

       CharArrayWriter has two constructors,

CharArrayWriter ( )

 

CharArrayWriter (int numChars)

 

       In the first form, a buffer with a default size is created. In the second, a buffer is created with a size equal to that specified by numChars. The buffer is held in the buf field of CharArrayWriter. The buffer size will be increased automatically, if needed.

 

Example

 

import java.io.*;

class CharArrayWriterDemo {

 

public static void main(String args[]) throws IOException { CharArrayWriter f = new CharArrayWriter (); String s = "This should end up in the array";

 

char buf[] = new char[s.length()]; s.getChars(0, s.length(), buf, 0); f.write(buf);

 

System.out.println ("Buffer as a string"); System.out.println (f.toString()); System.out.println ("Into array");

 

char c[] = f.toCharArray(); for (int i=0; i<c.length; i++) {

System.out.print(c[i]);

}

 

System.out.println ("\nTo a FileWriter ()"); FileWriter f2 = new FileWriter ("test.txt"); f.writeTo(f2);

f2.close();

 

System.out.println ("Doing a reset"); f.reset();

 

for (int i=0; i<3; i++) f.write('X');

System.out.println(f.toString());

}

 

}

 

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
Web or internet Programming : Java Programming : Java - I/O streaming |


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2024 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.