110 likes | 265 Views
Writers. a means of writing text. What are Writers?. Outputs a string of unicode chars Outputs a String Unicode is produced from ASCII input Manage the translation from non ASCII input ASCII – American Standard Code for Information Interchange
E N D
Writers a means of writing text
What are Writers? • Outputs a string of unicode chars • Outputs a String • Unicode is produced from ASCII input • Manage the translation from non ASCII input • ASCII – American Standard Code for Information Interchange • EBCDIC – Extended Binary Coded Decimal Interchange Code.
Java IO Character Streams - Reader
Java IO Character Streams - Writer PrintWriter
I/O Superclasses • Writer and OutputStream define similar APIs but for different data types. • Writer defines these methods for writing characters and arrays of characters: • int write(int c) • int write(char cbuf[]) • int write(char cbuf[], int offset, int length) • OutputStream defines the same methods but for bytes: • int write(int c) • int write(byte cbuf[]) • int write(byte cbuf[], int offset, int length)
Class Writer • All character stream writers are based on the class Writer (they extend Writer) • Some of the methods: • void write(int c) • void write(char[] cbuf) • void write(String str) • void flush() • void close()
Text Files • Information can be read from and written to text files by declaring and using the correct I/O streams • The FileReader class represents an input file containing character data • The FileReader and BufferedReader classes together create a convenient text file output stream • The FileWriter class represents a text output file, but with minimal support for manipulating data • Therefore, the PrintWriter class provides print and println methods
How do I build a writer? BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f))); .... bw.writeln(“this is a test”);
Text File I/O Streams • Input BufferedReader in = new BufferedReader(new FileReader(“foo.in”)); • Output PrintWriter out = new PrintWriter( new BufferedWriter(new FileWriter("foo.out"))); • BufferedWriter is not necessary but makes things more efficient • Output streams should be closed explicitly out.close();
import java.io.*; public class Copy { public static void main(String[] args) { String line; try { BufferedReader in = new BufferedReader(new FileReader(args[0])); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(args[1]))); while ((line = in.readLine()) != null) { out.println(line); } in.close(); out.close(); } catch (FileNotFoundException e) { System.out.println("The file " + args[0] + " was not found."); } catch (IOException e) { System.out.println(e); } } }
Writing a String to a file (WriteUtil) • public static void writeString(String s) { • FileWriter fw = getFileWriter("enter output file"); • try { • fw.write(s); • fw.close(); • } catch (IOException e) { • e.printStackTrace(); • } • }