A stream is a sequence of data. A program uses an input stream to read data from a source, one item at a time. A program uses an output stream to write data to a destination, one item at a time.
Byte Streams
Programs use byte streams to perform input and output of 8-bit bytes. All byte stream classes are descended from InputStream and OutputStream. There are many byte stream classes. The following are two such classesFileInputStream & FileOutputStream
read() method of FileInputStream is used to read bytes from the file. The bytes read from the file are returned in the form of int values. The return-type of int allows the read() method to return -1 when the End of File is reached.All open streams must be closed mandatorily to avoid serious resource leaks. Before calling the close() method, the stream variable must checked if it has an object reference.
Character Streams
The Java platform stores character values using Unicode conventions. Character stream I/O automatically translates this internal format to and from the local character set. In Western locales, the local character set is usually an 8-bit superset of ASCII.All character stream classes are descended from Reader and Writer. FileReader and FileWriter are specialized character stream classes for File I/O. Here also, the read() method is used to return an int value.
Character I/O usually occurs in bigger units than single characters. One common unit is the line. A line terminator can be a carriage-return/line-feed sequence("\r\n"). BufferedReader is an input character stream reader, used to buffer characters from an input character stream as per requirement. The readline() method, is used to read characters from a file until a '\n' or '\r' character is encountered.
Buffered Streams
When unbuffered I/O is performed, each read or write request is handled directly by the underlying OS. This is an inefficient process, as it involves disk access each time a read or write operation is performed. To reduce this kind of overhead, buffered I/O streams are provided. Buffered input streams read data from a memory aread known as a buffer; the native input API is called only when the buffer is empty. Similarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full.A program can convert an unbuffered stream into a buffered stream by wrapping. During wrapping, the unbuffered stream object is passed to the constructor for a buffered stream class. Example:
inputStream = new BufferedReader(new FileReader("xanadu.txt"));Some buffered output classes support autoflush, specified by an optional constructor argument. PrintWriter object flushes the buffer on every invocation of println or format methods.
outputStream = new BufferedWriter(new FileWriter("characteroutput.txt"));
No comments:
Post a Comment