The Writer class is the parent of all the writer classes in the java.io package. A writer is used for outputting data that is represented as characters. The Writer class contains the flush() and close() methods, which are similar to the ones in OutputStream. It also contains five write() methods:
public void write(int c). Writes a single character to the stream.
public void write(char [] c). Writes the array of characters to the stream.
public void write(char [] c,int offset, int length). Writes length number of characters in the array starting at the index specified by offset.
public void write(String s). Writes the given String to the stream.
public void write(String s, int offset, int length). Writes the specified subset of the given String to the stream.
import java.io.*; class FileWriterDemo { public static void main(String args[]) throws Exception { String source = "Now is the time for all good men " + " to come to the aid of their country " + " 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(); } }
The Reader class is the parent of all the reader classes in the java.io package. The Reader class has a close() and skip() method similar to the ones in InputStream.
public int read(). Reads a single character from the stream.
public int read(char [] c). Reads in a collection of characters and places them in the given array. The return value is the actual number of characters read.
public int read(char [] c, int offset, int length). Reads in a collection of characters and places them into the specified portion of the array.
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(); } }