Professional Documents
Culture Documents
• The stream classes are divided into two class hierarchies, based on the
data type (either characters or bytes) on which they operate i.e
•Character Stream
and
•Byte Stream
Character Streams
•The following figure shows the class hierarchies for the Reader and
Writer classes
Standard Streams
•JAVA provides support for standard I/O i.e. keyboard and
console
• System is a class in java.lang package
• in, out and err are public static and final variables in System
class
• in- object of InputStream
•out, err – objects of PrintStream
•Three predefined streams are available to a program
System.in – to read input from keyboard
System.out – to output the data produced by user program to
console
System.err – to output the error data produced by user
program to console
Reading and Writing Files
• Constructors
• FileReader(String fileName) throws FileNotFoundException
– Creates a FileReader from the given the name of the file
• Methods
• void flush() : Flushes this buffered output stream
• void write(byte[] b, int off, int len) : Writes len bytes from the
specified byte array starting at offset off to this buffered output
stream
• void write(int b) : Writes the specified byte to this buffered output
stream
•
BufferedReader
• BufferedReader(Reader)
• BufferedReader(Reader, int buffsize)
– Reads text from a character-input stream,
buffering characters so as to provide for the
efficient reading of characters, arrays, and lines
– Wrap a BufferedReader around any Reader
whose read() operations may be costly, such as
FileReaders and InputStreamReaders
•
Example
• BufferedReader in = new BufferedReader(new
FileReader("foo.in"));
• Methods
• void close()
• read() – read a character
• read(char[] cbuf, int off, int len)
•
• readLine() - Reads a line of text.
• A line is considered to be terminated by any one of a line
feed (‘\n’), a carriage return (‘\r’), or a carriage return
followed immediately by a line feed
BufferedWriter
• Constructors
• BufferedWriter(Writer out): Creates a buffered character-output stream that
uses a default-sized output buffer
• BufferedWriter(Writer out, int size): Creates a new buffered character-
output stream that uses an output buffer of the given size.
• Methods
• write(int arg) writes a single character that is specified by an integer
argument
• write(String arg, int offset, int length) writes String in the file according to
its arguments as mentioned in the Java Code
• newLine() breaks/separates line
• flush() flushes character from write buffer
• write(String s)
•
Sample program
• WAP to read a file input.txt line by line and copy the lines to another
file output.txt
Reading input from Console
Import java.io.Console;
Console console = System.console();
String input = console.readLine();
How to Use Pipe Streams