chapter 7. java io stream

Click here to load reader

Post on 16-Apr-2017

1.514 views

Category:

Technology

3 download

Embed Size (px)

TRANSCRIPT

Java2

Chapter 7Input/Output Streams1

Java Simplified / Session 22 / # of 45

1

Explain the concept of streamsExplain the standard input/output streamsExplain the ByteStream I/OStreamExplain the classes: FileInputStream and FileOutputStreamDescribe the Byte array I/O Discuss Filtered and Buffered I/O StreamsDiscuss the class RandomAccessFile, FileExplain the CharacterStreamExplain classes: Write, Reader, OutputStreamWriter, InputStreamReader, FileWriter, FileReader.Explain Serialization Objectives2

Java Simplified / Session 22 / # of 45A stream is a continuous group of data or a channel through which data travels from one point to another.Two kinds streams:Input stream receives data from a source into a program.Output stream sends data to a destination from the program.

Streams3

Java Simplified / Session 22 / # of 45Khi lp bt k chng trnh no trong mt ngn ng: vn vo ra d liu gia hng trnh v ngun d liu cng nh ch d liu l vn m ngi lp trnh cn phi quan tm. Lm th no ta c th truyn d liu cho mt chng trnh Java. C hai cch hiu qu thc hin iu ny: Thng qua mt ti nguyn tun t no nh file hoc qua mt my tnh khc. Thng qua giao din ngi my. Mc ch ca chng ny l xem xt cch truyn d liu cho mt chng trnh thng qua mt my tnh khc hay tp tin. 3

I/O Stream, ex4

Java Simplified / Session 22 / # of 45An I/O Stream represents an input source or an output destination. Many different kinds of sources and destinationsStream: many sources & destinations5

ConsoleDevicesFileNetwork- simple bytes, - primitive data types, - localized characters, - and objects

Java Simplified / Session 22 / # of 45When a stream is read/written, others threads are blocked.Exception: while reading/writing in stream, errors may be occurs. IOException is thrown.public static void main(String args[]) throws IOExceptionUsing try/ catch block:try { copy(fi, fo); } catch (IOException ex) { System.err.println(ex); }

Stream - exception6

Java Simplified / Session 22 / # of 45Standard input/output stream in Java is represented by three fields of the System class : System.in,System.out andSystem.err.

Standard input/output stream7

Java Simplified / Session 22 / # of 45Exampleclass SimpleIO {public static void main(String args[]){ byte bytearr[] = new byte[30];try { System.out.println("Enter a line: "); // Reads up to len bytes of data from the //input stream into an array of bytesSystem.in.read(bytearr,0,30); System.out.print("The line typed was: "); String str = new String(bytearr);//->str System.out.println(str); } catch(Exception e){ System.err.print("Error occurred: + e);} }}8

Java Simplified / Session 22 / # of 45Reads up to len bytes of data from the input stream into an array of bytes. An attempt is made to read as many as len bytes, but a smaller number may be read. The number of bytes actually read is returned as an integer. 8

There are two main categories of streams in Java : Byte Streams Provide input/output method in byteInputStream and OutputStream classes are at the top of their hierarchy. Character Streams Provide input/output method in character.

The java.io package9

Java Simplified / Session 22 / # of 45Hierarchy of classes and interfaces10

ObjectFileFileDescriptorRandomAccessFileDataInputDataOutputDataInputStreamBufferedInputStreamLineNumberInputStreamPushBackInputStreamFilterInputStreamInputStreamByteArrayInputStreamFileInputStreamOutputStreamFileOutputStreamFilterOutputStreamByteArrayOutputStreamBufferedOutputStreamDataOutputStreamPrintStream

Java Simplified / Session 22 / # of 45DataInput InterfaceIt is used to read bytes from a binary stream and reconstruct data in any of the java primitive types.Allows us to convert data that is in Java modified Unicode Transmission Format (UTF-8) to string form.DataInput interface defines a number of methods including methods for reading Java primitive data types.

Java Simplified / Session 22 / # of 45DataOutput InterfaceUsed to reconstruct data that is in any of the Java primitive types into a series of bytes and writes them onto a binary system. Allows us to convert a String into Java modified UTF-8 format and write it into a stream.All methods under DataOutput interface throw an IOException in case of an error.

Java Simplified / Session 22 / # of 45Two abstract are basic classes. They provide input/output methods in byte to file:InputStream classFile/ByteArray/Filter/ObjectInputStreamOutputStream classFile/ByteArray/Filter/ObjectOutputStream

Byte Streams13

Java Simplified / Session 22 / # of 45Defines how data is received.

The basic purpose: read data from an input stream.Defines methods to read dataMany subclasses:

InputStream class14

Java Simplified / Session 22 / # of 45Xc nh cch thc ly d liuCung cp cch c d liu t 1 lung nhp:nh ngha cc method c d liu. C cc lp con

14

Defines the way in which outputs are written to streams.

Used to write data to a stream.Defines methods to write data.Many subclasses:

OutputStream class15

Java Simplified / Session 22 / # of 45Xc nh cch ghi d liu vo lung outputnh ngha cc method ghi d liuCc cc class con

15

Methods of I/O Stream class:Support sub classesSub Classes: (constructors, methods)FileInputStream, FileOutputStreamByteArrayInputStream, ByteArrayOutputStreamFilterInputStream, FilterOutputStreamBufferedInputStream, BufferedOutputStream

I/O Stream Class16

Java Simplified / Session 22 / # of 45Read every byte from file (in byte)int read() Return value (8 low bits of int): 0-255; end of stream: -1int read(byte[] b) Read data from input stream to array bint read(byte[] b, int offs, int len) Read data from input stream to array b, start offs, save len bytespublic int available()Numbers data bytes left in StreamException: throws IOException

Methods in InputStream class17

Java Simplified / Session 22 / # of 45c tng byte, nhng cho li gi tr kiu int.Cc byte c c s c gn vo 8bit thp ca kiu int, nhng bit cn li c gn gi tr 017

public long skip(long count) Skip count data bytes public void reset() Redefine recent marked position in InputStream . public void close() Close file. Release resourceException: throws IOExceptionpublic synchronized void mark(int readLimit) Mark current position in InputStream public boolean markSupported() True: support mark, flase: not supportMethods in InputStream class18

Java Simplified / Session 22 / # of 45Write every byte to file:void write(int b) Write every byte to file (8 low bits of int). b = 0-255; others, b=b mod 256void write(byte[] b) Write bytes from output stream to array bvoid write(byte[] b, int offs, int l)Write bytes from output stream to array b, start offs, save len bytesException: throws IOExceptionvoid flush() Close fileMethods in OutputStream class19

Java Simplified / Session 22 / # of 45Thc hin ghi tng byte (value: 0->256 = 8bit thp). Nu truyn vo gi tr >255, 0) { char ch = (char) f.read();System.out.print(ch);}23

Java Simplified / Session 22 / # of 45TV/ no TV23

Vit d liu dng byte t OutputStream vo file.Its constructors are: FileOutputStream(String filename) : Creates an OutputStream, to write bytes to a file.FileOutputStream(File name) : Creates an OutputStream, to write bytes to a file.FileOutputStream(String filename, boolean flag) : Creates an OutputStream, to write bytes to a file. If flag is true, file is opened in append mode.Exception: FileNotFoundExceptionFileOutputStream class24

Java Simplified / Session 22 / # of 45Nhp d liuKhai bo 1 mng byte nhn d liu nhp voTo 1 lung FileOutputStream (filename)Ghi d liu t OutputStream vo file

Thc hin ghi byte d liu vo File25

Java Simplified / Session 22 / # of 45Example: write data (bytes) to fileimport java.io.*;class FileOutputDemo {public static void main(String args[]) {String s="cng ha x hi VN abcd";byte b[] = s.getBytes();try {FileOutputStream fos = new FileOutputStream("aa.txt"); fos.write(b,0,b.length); System.out.println(b.length + " bytes are written!");} catch(IOException e) { System.out.println("Error creating file!");} }}26

Java Simplified / Session 22 / # of 45Ok, TV26

Ex:Copy a file with read(byte[] data) and write(byte[] data)public class CopyFileTV_ex { public static void main(String[] args) throws IOException { FileInputStream fin = null; FileOutputStream fout = null; // File fil = new File("a1.txt"); fin = new FileInputStream("a1.txt");//or: (fil) fout = new FileOutputStream("xyz.txt"); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = fin.read(buffer)) > 0) { fout.write(buffer, 0, bytesRead); } fin.close(); fout.close(); }27int size = 0;try {size = SFile.available();byte[] b = new byte[size];SFile.read(b,0,size);DFile.write(b,0,size);} catch (IOException e) {// TODO e.printStackTrace();}

Java Simplified / Session 22 / # of 45Fix: Not TV.Properties: Atribute: other: UTF-827

Dng 1 mng byte nh l ngun d liu vo (not file)Methods : read(), skip(), reset(), available(), (from parent class)Its constructors are :ByteArrayInputStream(byte b[]): Creates a ByteArrayInputStream with b as the input source.ByteArrayInputStream(byte b[]), int start, int num): Creates a ByteArrayInputStream that begins with the character at start position and is num bytes long.ByteArrayInputStream class28

Java Simplified / Session 22 / # of 45Khai bo 1 mng byte (hoc String), nhn d liu To mt lung nhp mng byte t mng byte (hoc String)c d liu t lung nhp mng byte (String)C th in ra mn hnh

String text = "Converting String to InputStream Example";InputStream is = new ByteArrayInputStream(text.getBytes("UTF-8"));

Cch thc c d liu t lung mng byte29

Java Simplified / Session 22 / # of 45Ex: Convert string into InputStream using ByteArrayInputStream classimport java.io.*;class ByteDemo {public static void main (String []args) {String str = "c lp t do hnh phc Vit Nam";byte[] b = str.getBytes(); InputStream bais = new ByteArrayInputStream(b,0,b.length);int ch;while((ch = bais.read()) != -1)System.out.print((char) ch);//ep kieuSystem.out.println();bais.reset(); //using reset ( ) method and again readingch = 0;while((ch = bais.read()) != -1)System.out.print((char) ch);}}30

Java Simplified / Session 22 / # of 45No TV30

To ra mt lung xut trn 1 mng byte.two constructors.ByteArrayOutputStream(int size)used to set the output byte array to an initial size.ByteArrayOutputStream()sets the output buffer to a default size. Additional methods like:String toByteArray() and String toString()convert the stream to a byte array and String object respectively.size(): size of bufferByteArrayOutputStream31

Java Simplified / Session 22 / # of 45Khai bo 1 mng byte, nhn d liu cn ghiTo mt lung xut mng byteGhi d liu t mng byte vo lung xut mng byteC th in ra mn hnh (chuyn lung sang string)

Cch thc ghi d liu vo lung mng byte32

Java Simplified / Session 22 / # of 45Ex: Convert OutputStream to String using ByteArrayOutputStream classimport java.io.*;class ByteOutDemo {public static void main (String []args) throws IOException {String str = "Jack and Jill went up the hill";byte[] b = str.getBytes();ByteArrayOutputStream b1 = new ByteArrayOutputStream();b1.write(b);System.out.println("Writing the contents of a ByteArrayOutputStream");System.out.println(b1.toString());}}33

Java Simplified / Session 22 / # of 45Ex ByteArrayIOStream34public class ByteArrayIOApp { public static void main(String args[]) throws IOException { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); String s = "This is a test."; for (int i = 0; i < s.length(); ++i) outStream.write(s.charAt(i)); System.out.println("outstream: " + outStream); System.out.println("size: " + outStream.size()); ByteArrayInputStream inStream; inStream = new ByteArrayInputStream(outStream.toByteArray()); int inBytes = inStream.available(); System.out.println("inStream has" + inBytes + "available bytes"); byte inBuf[] = new byte[inBytes]; int bytesRead = inStream.read(inBuf, 0, inBytes); System.out.println(bytesRead + " bytes were read"); System.out.println("They are: " + new String(inBuf)); }}

Java Simplified / Session 22 / # of 45Cc lung InputStream v OuptutStream l cc lung th. Java cung cp mt s lp lc ta gn cc lung d liu th vi chng nhm mc ch chuyn i qua li gia cc byte v cc khun dng d liu khc. Filter Streams c th kt ni vi cc Stream khc v x l d liu Cc lung lc cng c hai loi l:lung c (reader) v lung ghi (writer). Filter Streams

35

Java Simplified / Session 22 / # of 45

35

L lp c s ca all cc lp, lm nhim v nh b lc ca cc lung input/outputCc lp con:FilterInputStream: lp c s ca lung nhpprotected FilterInputStream(InputStream in)FilterOutputStream: lp c s ca lung xutpublic FilterOutputStream(OutputStream out)BufferedInputStream /BufferedOutputStream.

Filter Input and Output classes36

Java Simplified / Session 22 / # of 45L lp c s ca all cc lp lm nhim v nh b lc ca cc lung input/output36

Mt buffer l khu vc lu tr tm d liu.Bng cch lu tr d liu trong buffer, qu trnh c/ghi s nhanh hn Java dng buffered I/O lm b lu tr d liu tm khi c/ghi d liuHai lp c s dng c/ghi d liu theo tng buffer byte: BufferedInputStreamBufferedOutputStream Vic lc trn buffer s c tin hnh gia chng trnh v ch ca lung buffer. Buffered I/O classes37

Java Simplified / Session 22 / # of 45Cc lung InputStream v OuptutStream l cc lung th. Java cung cp mt s lp lc ta gn cc lung d liu th vi chng nhm mc ch chuyn i qua li gia cc byte v cc khun dng d liu khc. Cc lung lc cng c hai loi l:lung c (reader) v lung ghi (writer). Kt ni cc lung lc vi nhau. Cc lung lc c kt ni vi cc lung thng qua cc constructor ca chng. 37

Lp BufferedInputStream :C mt mng byte c s dng lm vng m. Khi gi c lung read(), trc tin n nhn d liu c yu cu t vng m. (Khi vng m ht d liu thc s n mi c d liu t ngun)c cng nhiu d liu t ngun vo vng mtwo constructors: BufferedInputStream(InputStream is): Creates a buffered input stream for the specified InputStream instance.

BufferedInputStream(InputStream is, int size): Creates a buffered input stream of a given size for the specified InputStream instance.BufferedInputStream38

Java Simplified / Session 22 / # of 45Ex Read from String with BufferedInputStream39import java.io.BufferedInputStream;public class BuffInput {public static void main(String[] args) {System.out.println("Enter a line:");BufferedInputStream bi = new BufferedInputStream(System.in);try {for (int i=0; ikh tun t ha kh tun t ha

Java Simplified / Session 22 / # of 45Object streams support I/O of objectsLike Data streams support I/O of primitive data typesThe object has to be Serializable type An object stream can contain a mixture of primitive and object values.Input and Output of Complex Object:Object Stream 82

Java Simplified / Session 22 / # of 45Invoking writeObject(a) writes not just a, but all the objects necessary to reconstitute a, so the other four objects in this web are written also When a is read back by readObject, the other four objects are read back as well, and all the original object references are preserved.82

There are two streams in java.io: ObjectInputStream and ObjectOutputStream .They are like any other input stream and output stream with the difference that they can read and write objectsSerialization 83

Java Simplified / Session 22 / # of 45Tun t ha l qu trnh chuyn tp hp cc th hin i tng cha cc tham chiu ti cc i tng khc thnh mt lung byte tuyn tnh (tun t), lung ny c th c gi i qua mt Socket, c lu vo tp tin hoc c x l di dng mt lung d liu.

83

This class has methods that support object serialization. ObjectInputStream is responsible for reading objects from a input stream.ObjectInputStream84

InputStreamObjectInputDataInput

ObjectInputStreamImp

Java Simplified / Session 22 / # of 45This class extends the InputStream class and implements the ObjectInput interface.ObjectInput interface extends the DataInput interface and has methods that support object serialization.

84

ObjectOutputStream is responsible for writting objects to the output stream ObjectOutputStream 85

OutputStreamObjectOutnputDataOutnput

ObjectOutputStreamImp

Java Simplified / Session 22 / # of 45public class writeObj { public static void main(String[] args) throws Exception { Junk obj1 = new Junk("L Xun Anh"); Junk obj2 = new Junk("L Quc Ba"); ObjectOutputStream objectOut = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("b.txt")));objectOut.writeObject(obj1); // Write object objectOut.writeObject(obj2); // Write object objectOut.close(); // Close the output streamObjectInputStream objectIn = null; int Count = 0; Junk object = null;objectIn = new ObjectInputStream(new BufferedInputStream(new FileInputStream("b.txt")));while (Count < 2) { object = (Junk) objectIn.readObject(); Count++; System.out.println("Object " + Count + ": " + object.toStr()); } objectIn.close(); }}Example Serialization86class Junk implements Serializable { String str; public Junk(String s) { str = s; } public String toSt(){ return str; }}

Java Simplified / Session 22 / # of 45

86

Explain the concept of streamsExplain the standard input/output streamsExplain the ByteStream I/OStreamExplain the classes: FileInputStream and FileOutputStreamDescribe the Byte array I/ODiscuss Filtered and Buffered I/O operationsDiscuss the class RandomAccessFile, FileExplain the CharacterStreamExplain classes: Write, Reader, OutputStreamWriter, InputStreamReader, FileWriter, FileReader.Explain BufferedStreamExplain Serialization Summarization87

Java Simplified / Session 22 / # of 45