Sunday, March 11, 2012

Java IO

Programs use byte streams to perform input and output of 8-bit bytes. All byte stream classes are descended from InputStream and OutputStream.
InputStream.read();
OutputStream.write(c)
both are abstract classes.
FileInputStream in = null;         FileOutputStream out = null;          try {             in = new FileInputStream("xanadu.txt");             out = new FileOutputStream("outagain.txt");
Closing a stream when it's no longer needed is very important — so important that CopyBytes uses afinally block to guarantee that both streams will be closed even if an error occurs. This practice helps avoid serious resource leaks. 
all other stream types are built on byte streams. 
--------------
All character stream classes are descended from Reader and Writer. 
Reader.read();
Writer.write(c)
Line-Oriented IO has to use bufferedReader and BufferedWriter
--
Above are unbuffered IO,This means each read or write request is handled directly by the underlying OS.
to reduce overhead, the Java platform implements buffered I/O streams. 
using wrapping approach
inputStream = new BufferedReader(new FileReader("xanadu.txt")); outputStream = new BufferedWriter(new FileWriter("characteroutput.txt"));
Decorator Design pattern!!!
-----
Objects of type Scanner are useful for breaking down formatted input into tokens and translating individual tokens according to their data type. 
 s = new Scanner(new BufferedReader(new FileReader("xanadu.txt")));              while (s.hasNext()) {                 System.out.println(s.next());             }
s.useDelimiter(",\\s*");
s.hasNextDouble();
---
Stream objects that implement formatting are instances of either PrintWriter, a character stream class, or PrintStream, a byte stream class. 
 System.out  is PrintStream 

No comments:

Post a Comment