18- Understanding java streams java

31
Understanding Java Streams java.io .* Shahjahan Samoon

description

 

Transcript of 18- Understanding java streams java

  • 1. Understand the stream Know the difference between byte and character streams Know Javas byte stream classes Know Javas character stream classes Know the predefined streams Use byte streams Use byte streams for file I/O Read and write binary data Use character streams Use character streams for file I/O Object Serialization Object Deserialization

2. A stream is an abstract representation of an input or output device that is a source of, or destination for, data. You can write data to a stream and read data from a stream. You can visualize a stream as a sequence of bytes that flows into or out of your program Java programs perform I/O through streams. A stream is an abstraction that either produces or consumes information. A stream is linked to a physical device by the Java I/O system. All streams behave in the same manner, even if the actual physical devices they are linked to differ. Thus, the same I/O classes and methods can be applied to any type of device. For example, the same methods that you use to write to the console can also be used to write to a disk file. Java implements streams within class hierarchies defined in the java.io package. 3. I/O = Input/Output In this context it is input to and output from programs Input can be from keyboard or a file Output can be to display (screen) or a file Advantages of file I/O permanent copy output from one program can be input to another input can be automated (rather than entered manually) 4. Stream: an object that either delivers data to its destination (screen, file, etc.) or that takes data from a source (keyboard, file, etc.) it acts as a buffer between the data source and destination Input stream: a stream that provides input to a program System.in is an input stream Output stream: a stream that accepts output from a program System.out is an output stream A stream connects a program to an I/O object System.out connects a program to the screen System.in connects a program to the keyboard 5. All data and programs are ultimately just zeros and ones each digit can have one of two values, hence binary bit is one binary digit byte is a group of eight bits Text files: the bits represent printable characters one byte per character for ASCII, the most common code for example, Java source files are text files so is any file created with a "text editor" Binary files: the bits represent other types of encoded information, such as executable instructions or numeric data these files are easily read by the computer but not humans they are not "printable" files actually, you can print them, but they will be unintelligible "printable" means "easily readable by humans when printed" 6. Text files are more readable by humans Binary files are more efficient computers read and write binary files more easily than text Java binary files are portable they can be used by Java on different machines Reading and writing binary files is normally done by a program text files are used only to communicate with humans Java Text Files Source files Occasionally input files Occasionally output files Java Binary Files Executable files (created by compiling source files) Usually input files Usually output files 7. Number: 127 (decimal) Text file Three bytes: 1, 2, 7 ASCII (decimal): 49, 50, 55 ASCII (octal): 61, 62, 67 ASCII (binary): 00110001, 00110010, 00110111 Binary file: One byte (byte): 01111110 Two bytes (short): 00000000 01111110 Four bytes (int): 00000000 00000000 00000000 01111110 8. Not buffered: each byte is read/written from/to disk as soon as possible little delay for each byte A disk operation per byte---higher overhead Buffered: reading/writing in chunks Some delay for some bytes Assume 16-byte buffers Reading: access the first 4 bytes, need to wait for all 16 bytes are read from disk to memory Writing: save the first 4 bytes, need to wait for all 16 bytes before writing from memory to disk A disk operation per a buffer of bytes---lower overhead 9. Modern versions of Java define two types of Streams: byte and character. Byte streams provide a convenient means for handling input and output of bytes. Byte streams are used, for example, when reading or writing binary data. They are especially helpful when working with files. Character streams are designed for handling the input and output of characters. Character streams use Unicode and, therefore, can be internationalized. Also, in some cases, character streams are more efficient than byte streams. At the lowest level, all I/O is still byte-oriented. The character-based streams simply provide a convenient and efficient means for handling characters. 10. Byte streams are defined by using two class hierarchies. At the top of these are two abstract classes: InputStream and OutputStream. InputStream defines the characteristics common to byte input streams and OutputStream describes the behavior of byte output streams. From InputStream and OutputStream are created several concrete subclasses that offer varying functionality and handle the details of reading and writing to various devices, such as disk files. 11. Character streams are defined by using two class hierarchies topped by these two abstract classes: Reader and Writer. Reader is used for input, and Writer is used for output. Concrete classes derived from Reader and Writer operate on Unicode character streams. From Reader and Writer are derived several concrete subclasses that handle various I/O situations. In general, the character-based classes parallel the byte-based classes. 12. As you know, all Java programs automatically import the java.lang package. This package defines a class called System, which encapsulates several aspects of the run-time environment. Among other things, it contains three predefined stream variables, called in, out, and err. These fields are declared as public and static within System. This means that they can be used by any other part of your program and without reference to a specific System object. System.out refers to the standard output stream. By default, this is the console. System.in refers to standard input, which is by default the keyboard. System.err refers to the standard error stream, which is also the console by default. However, these streams can be redirected to any compatible I/O device. 13. BufferedInputStream BufferedOutputStream ByteArrayInputStream ByteArrayOutputStream DataInputStream DataOutputStream FileInputStream FileOutputStream FilterInputStream FilterOutputStream InputStream ObjectInputStream ObjectOutputStream OutputStream PipedInputStream PipedOutputStream PrintStream PushbackInputStream RandomAccessFile SequenceInputStream 14. BufferedReader BufferedWriter CharArrayReader CharArrayWriter FileReader FileWriter FilterReader FilterWriter InputStreamReader LineNumberReader OutputStreamWriter PipedReader PipedWriter PrintWriter PushbackReader Reader StringReader StringWriter 15. import java.io.*; class ReadBytes { public static void main(String args[]) throws Exception { byte data[] = new byte[10]; System.out.println("Enter some characters."); System.in.read(data); System.out.print("You entered: "); for(int i=0; i < data.length; i++) System.out.print((char) data[i]); } } 16. class WriteDemo { public static void main(String args[]) { int b; b = 'X'; System.out.write(b); System.out.write('n'); } } 17. import java.io.*; class ShowFile { public static void main(String args[]) throws IOException { int i; FileInputStream fin = new FileInputStream(args[0]); do { i = fin.read(); if(i != -1) System.out.print((char) i); } while(i != -1); fin.close(); } } 18. import java.io.*; class CopyFile { public static void main(String args[]) throws Exception { int i; FileInputStream fin = new FileInputStream(args[0]); FileOutputStream fout = new FileOutputStream(args[1]); do { i = fin.read(); if(i != -1) fout.write(i); } while(i != -1); fin.close(); fout.close(); } } 19. import java.io.*; class RWData { public static void main(String args[]) throws Exception { DataOutputStream dataOut = new DataOutputStream(new FileOutputStream("testdata")); int i = 10; double d = 1023.56; boolean b = true; System.out.println("Writing " + i); dataOut.writeInt(i); System.out.println("Writing " + d); dataOut.writeDouble(d); System.out.println("Writing " + b); dataOut.writeBoolean(b); System.out.println("Writing " + 12.2 * 7.4); dataOut.writeDouble(12.2 * 7.4); dataOut.close(); System.out.println(); DataInputStream dataIn = new DataInputStream(new FileInputStream("testdata")); i = dataIn.readInt(); System.out.println("Reading " + i); d = dataIn.readDouble(); System.out.println("Reading " + d); b = dataIn.readBoolean(); System.out.println("Reading " + b); d = dataIn.readDouble(); System.out.println("Reading " + d); dataIn.close(); } } 20. import java.io.*; class CompFiles { public static void main(String args[])throws Exception { int i=0, j=0; FileInputStream f1 = new FileInputStream(args[0]); FileInputStream f2 = new FileInputStream(args[1]); do { i = f1.read(); j = f2.read(); if(i != j) break; } while(i != -1 && j != -1); if(i != j) System.out.println("Files differ."); else System.out.println("Files are the same."); f1.close(); f2.close(); } } 21. import java.io.*; class ReadChars { public static void main(String args[]) throws Exception { char c; BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); System.out.println("Enter characters, period to quit."); do { c = (char) br.read(); System.out.println(c); } while(c != '.'); } } 22. import java.io.*; Create BufferedReader class ReadLines { public static void main(String args[]) Throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str; System.out.println("Enter lines of text."); System.out.println("Enter 'stop' to quit."); do { str = br.readLine(); System.out.println(str); } while(!str.equals("stop")); } } 23. import java.io.*; public class PrintWriterDemo { public static void main(String args[]) { PrintWriter pw = new PrintWriter(System.out, true); int i = 10; double d = 123.65; pw.println("Using a PrintWriter."); pw.println(i); pw.println(d); pw.println(i + " + " + d + " is " + (i+d)); } } 24. import java.io.*; class KtoD { public static void main(String args[]) throws Exception { String str; FileWriter fw = new FileWriter("test.txt"); BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); System.out.println("Enter text ('stop' to quit)."); do { System.out.print(": "); str = br.readLine(); if(str.compareTo("stop") == 0) break; str = str + "rn"; // add newline fw.write(str); } while(str.compareTo("stop") != 0); fw.close(); } } 25. import java.io.*; class DtoS { public static void main(String args[]) throws Exception { FileReader fr = new FileReader("test.txt"); BufferedReader br = new BufferedReader(fr); String s; while((s = br.readLine()) != null) { System.out.println(s); } fr.close(); } } 26. class MyClass implements Serializable { double id; String name; String course; public MyClass(double i, String n, String c) { id=i; name=n;course=c; } public String toString() { return ID: " + id + nNAME: " + name + nCOURSE: "+ course; } } 27. import java.io.*; public class SerializationDemo { public static void main(String args[]) throws Exception{ // Object serialization MyClass object1 = new MyClass(2342, Shahjahan, Java); System.out.println("object1: " + object1); FileOutputStream fos = new FileOutputStream("serial"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(object1); oos.flush(); oos.close(); } 28. // Object deserialization MyClass object2; FileInputStream fis = new FileInputStream("serial"); ObjectInputStream ois = new ObjectInputStream(fis); object2 = (MyClass)ois.readObject(); ois.close(); System.out.println("object2: " + object2); } } 29. import java.util.zip.*; import java.io.*; public class GZIPcompress { public static void main(String[] args)throws IOException { BufferedReader in = new BufferedReader( new FileReader(args[0])); BufferedOutputStream out = new BufferedOutputStream( new GZIPOutputStream( new FileOutputStream("test.gz"))); int c; while((c = in.read()) != -1) out.write(c); in.close(); out.close(); BufferedReader in2 = new BufferedReader( new InputStreamReader(new GZIPInputStream( new FileInputStream("test.gz")))); String s; while((s = in2.readLine()) != null) System.out.println(s); } } 30. import java.io.*; import java.util.zip.*; public class Streams{ public static void main(String[] args) throws Exception { FileInputStream in = new FileInputStream("C:/Users/Shahjahan samoon/Desktop/abc.txt"); ZipOutputStream out = new ZipOutputStream(new FileOutputStream("D:/tmp.zip")); out.putNextEntry(new ZipEntry("abc.txt")); int count; while ((count = in.read()) != -1) { System.out.println(); out.write(count); } out.close(); in.close(); } }