Bài giảng Công nghệ Java - Chương 8: Java Input/Output
Stream
• Stream:
– dòng thông tin giữa 2 tác nhân (mức cao)
– một dãy tuần tự các byte (mức thấp)
• Một stream được gắn với một nguồn (source), hay một đích
(destination)
• Stream operations:
– open stream
– close stream
– read
– write
– seek
• Input stream: support reading functions
• Output stream: support writing functions
• Filter stream: buffer
Bạn đang xem 20 trang mẫu của tài liệu "Bài giảng Công nghệ Java - Chương 8: Java Input/Output", để tải tài liệu gốc về máy hãy click vào nút Download ở trên
Tóm tắt nội dung tài liệu: Bài giảng Công nghệ Java - Chương 8: Java Input/Output
CÔNG NGHỆ JAVA CH8. JAVA INPUT/OUTPUT Quang Dieu Tran PhD 4/7/2018 1 INPUT/OUTPUT STREAMS 1. Stream concepts 2. Input Streams 3. Output Streams 4. Reader 5. Writer 6. Object Serialization 7. Object Input Stream 8. Object Output Stream 4/7/2018 2 Stream concepts • Data exchange • Data exchange type: Character, Object, voice, picture, audio, video... Program File Memory Network Program information 4/7/2018 3 Stream • Stream: – dòng thông tin giữa 2 tác nhân (mức cao) – một dãy tuần tự các byte (mức thấp) • Một stream được gắn với một nguồn (source), hay một đích (destination) • Stream operations: – open stream – close stream – read – write – seek • Input stream: support reading functions • Output stream: support writing functions • Filter stream: buffer 4/7/2018 4 This image cannot currently be displayed. Hình 1: Chương trình xử lý dữ liệu từ 1 input stream Hình 2: Chương trình ghi dữ liệu ra output stream Input & Output Stream 4/7/2018 5 Trình tự đọc/ ghi dòng open input stream while (more information){ read information process information } close input stream open output stream while (more information){ get information from ... write information } close output stream Đọc thông tin từ input stream Ghi thông tin vào output stream 4/7/2018 6 Các loại stream trong package java.io • các lớp trong gói java.io được thiết kế gồm 2 nhóm chính: – Nhóm input/output stream, hay nhóm hướng byte – Nhóm reader/writer, hay nhóm hướng ký tự (unicode) 4/7/2018 7 Nhóm input/output stream • Được gọi là nhóm hướng byte, vì thao tác đọc/ghi áp dụng cho 1 hoặc nhiều byte, chỉ giới hạn xử lý các byte 8 bits ISO-Latin-1. Rất thích hợp khi cần xử lý dữ liệu nhị phân như ảnh, âm thanh, binary files... • Các input stream được mở rộng từ lớp InputStream (Abstract class) • Các output stream được mở rộng từ lớp OutputStream (Abstract class) 4/7/2018 8 Nhóm input stream 4/7/2018 9 Nhóm output stream 4/7/2018 10 Nhóm reader/writer • Được gọi là nhóm hướng ký tự, vì thao tác đọc/ghi áp dụng cho 1 hoặc nhiều ký tự Unicode (1 character = 2bytes) 4/7/2018 11 Nhóm Writer 4/7/2018 12 Các loại các stream (tt) • java IO cũng cung cấp cách thức kết gắn stream với các loại tác nhân khác như bộ nhớ, file ... • Các lớp InputStreamReader và OutputStreamWriter cung cấp sự chuyển đổi giữa stream và reader/writer • Xem bảng phân loại tóm tắt để biết thêm chi tiết 4/7/2018 13 Tổng quát về các Streams I/O Streams Mô tả khái quát M e m o r y CharArrayReader CharArrayWriter ByteArrayInput- Stream ByteArrayOutput- Stream Đọc/ghi từ/vào bộ nhớ. Tạo stream từ một mảng, tiếp theo dùng các phương thức đọc/ghi để đọc/ghi từ/vào mảng. Tác vụ đọc sẽ lấy dữ liệu từ mảng Tác vụ ghi sẽ ghi ra mảng StringReader StringWriter StringBuffer- InputStream StringReader để đọc các ký tự từ một String trong bộ nhớ. StringWriter để ghi vào String. StringBufferInputStream tương tự như StringReader. Sự khác biệt chỉ là StringBufferInputStream đọc các bytes từ một đối tượng StringBuffer 4/7/2018 14 Tổng quát về các Streams Pipe PipedReader PipedWriter PipedInputStream PipedOutputStream Hiện thực các thành phần input và output của một pipe. Pipes được dùng như một kênh truyền, nối output của một thread vào input của một thread khác. File FileReader FileWriter FileInputStream FileOutputStream Được gọi là các file streams. File streams dùng để đọc/ghi từ/vào file trên file system. Nối SequenceInput- Stream (concatenation) Nối nhiều input streams thành một input stream. 4/7/2018 15 Tổng quát về các Streams Object Serial- ization ObjectInputStream ObjectOutputStream Dùng khi cần lưu trữ, khôi phục, hoặc truyền toàn bộ đối tượng. Chuyển đổi dạng dữ liệu (Data Conver- sion) DataInputStream DataOutputStream Thuận tiện khi cần đọc/ghi các kiểu dữ liệu cơ bản (primitive data types) như int, double, ... Counting LineNumberReader LineNumberInput- Stream Theo dõi số hàng trong khi đọc 4/7/2018 16 Tổng quát về các Streams Printing PrintWriter PrintStream Rất thuận tiện khi cần kết xuất, dễ đọc với người. System.out là một đối tượng thuộc lớp PrintStream. Đệm (Buffer- ing) BufferedReader BufferedWriter bufferedInput-Stream BufferedOutput-Stream Đệm dữ liệu trong các thao tác đọc/ghi. Đệm dữ liệu cải thiện tốc độ đọc ghi vì giảm số lần truy xuất thiết bị. Lọc dữ liệu (Filtering) FilterReader FilterWriter FilterInputStream FilterOutputStream Các lớp abstract này định nghĩa các giao tiếp cho các filter streams lọc dữ liệu trong khi đọc/ghi. 4/7/2018 17 Tổng quát về các Streams C h u yển đ ổi b yte k ý tự (C on vertin g b etw een B ytes a n d C h a racters) I n p u t S t r e a m R e a d e r O u t p u t S t r e a m W r i t e r Cặp reader/writer này là cầu nối giữa các byte streams và character streams. Một InputStreamReader đọc các bytes từ một InputStream và chuyển các bytes đó thành các ký tự. Một OutputStreamWriter chuyển các ký tự sang các bytes, và ghi các bytes đó vào một OutputStream. Quá trình chuyển đổi sẽ sử dụng bộ mã mặc định nếu không được chỉ định rõ. Gọi System.getProperty("file.encoding") để lấy về tên bộ mã mặc định. 4/7/2018 18 Các lớp IO • InputStream, OutputStream, Reader và Writer là các lớp abstract: – Các lớp input stream được mở rộng từ lớp InputStream – Các lớp reader được mở rộng từ lớp Reader – Các lớp output stream được mở rộng từ lớp OutputStream – Các lớp writer được mở rộng từ lớp Writer • 2 lớp InputStream và Reader cung cấp những phương thức read tương đối giống nhau. • 2 lớp OutputStream và Writer cung cấp những phương thức write tương đối giống nhau. 4/7/2018 19 InputSream • Low-Level Input Stream Purpose of Stream • ByteArrayInputStream Reads bytes of data from an memory array • FileInputStream Reads bytes of data from a file on the local file system • PipedInputStream Reads bytes of data from a thread pipe • StringBufferInputStream Reads bytes of data from a string • SequenceInputStream Reads bytes of data from two or more low-level streams, switching from one stream to the next when the end of the stream is reached • System.in Reads bytes of data from the user console 4/7/2018 20 The java.io.InputStream Class • int available() throws java.io.IOException— returns the number of bytes currently available for reading. • void close() throws java.io.IOException— closes the input stream and frees any resources (such as file handles or file locks) associated with the input stream. • int read() throws java.io.IOException— returns the next byte of data from the stream. When the end of the stream is reached, a value of –1 is returned. • int read(byte[] byteArray) throws java.io.IOException— reads a sequence of bytes and places them in the specified byte array. This method returns the number of bytes successfully read, or –1 if the end of the stream has been reached. • int read(byte[] byteArray, int offset, int length) throws java.io.IOException, java.lang.IndexOutOfBoundsException— reads a sequence of bytes, placing them in the specified array at the specified offset, and for the specified length, if possible. 4/7/2018 21 The java.io.InputStream Class • long skip(long amount) throws java.io.IOException— reads, but ignores, the specified amount of bytes. These bytes are discarded, and the position of the input stream is updated. The skip method returns the number of bytes skipped over, which may be less than the requested amount. • The following code fragment reads 10 bytes from the InputStream in and stores them in the byte array input. However, if end of stream is detected, the loop is terminated early: byte[] input = new byte[10]; for (int i = 0; i < input.length; i++) { int b = in.read( ); if (b == -1) break; input[i] = (byte) b; } 4/7/2018 22 The java.io.InputStream Class • For example, you may try to read 1 024 bytes from a network connection, when only 512 have actually arrived from the server. The rest are still in transit. They'll arrive eventually, but they aren't available now. byte[] input = new byte[1024]; int bytesRead = in.read(input); • It attempts to read 1 024 bytes from the InputStream in into the array input. However, if only 512 bytes are available, then bytesRead will be set to 512. To guarantee that all the bytes you want are actually read, you must place the read in a loop that reads repeatedly until the array is filled. int bytesRead = 0; int bytesToRead = 1024; byte[] input = new byte[bytesToRead]; while (bytesRead < bytesToRead) { bytesRead += in.read(input, bytesRead, bytesToRead - bytesRead); } 4/7/2018 23 The java.io.File Class • An abstract representation of file and directory pathnames. • For UNIX platforms, the prefix of an absolute pathname is always "/". Relative pathnames have no prefix. • For Microsoft Windows platforms, the prefix of a pathname that contains a drive specifier consists of the drive letter followed by ":" and possibly followed by "\\" if the pathname is absolute (D:\\myfolder\\t.txt). A relative pathname that does not specify a drive has no prefix. • public File(File parent, String child) – Creates a new File instance from a parent abstract pathname and a child pathname string. • public File(String parent, String child) – Creates a new File instance from a parent pathname string and a child pathname string. 4/7/2018 24 The java.io.File Class • public File(String pathname) – Creates a new File instance by converting the given pathname string into an abstract pathname. If the given string is the empty string, then the result is the empty abstract pathname. • public String getPath() – Converts this abstract pathname into a pathname string. • public boolean isAbsolute() – Tests whether this abstract pathname is absolute. • public String getAbsolutePath() – Returns the absolute pathname string of this abstract pathname. • public boolean canRead() – Tests whether the application can read the file denoted by this abstract pathname. 4/7/2018 25 The java.io.File Class • public boolean canWrite() – Tests whether the application can modify the file denoted by this abstract pathname • public boolean exists() – Tests whether the file or directory denoted by this abstract pathname exists. • public boolean isDirectory() – Tests whether the file denoted by this abstract pathname is a directory. • public boolean isFile() – Tests whether the file denoted by this abstract pathname is a normal file. • public boolean isHidden() – Tests whether the file named by this abstract pathname is a hidden file. 4/7/2018 26 The java.io.File Class • public long length() Returns the length (the zise in Kbyte) of the file denoted by this abstract pathname. The return value is unspecified if this pathname denotes a directory. • public boolean delete() Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the directory must be empty in order to be deleted. • public String[] list() Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname. • public String[] list(FilenameFilter filter) Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter. The behavior of this method is the same as that of the list() method, except that the strings in the returned array must satisfy the filter. If the given filter is null then all names are accepted. 4/7/2018 27 The java.io.File Class • public File[] listFiles() Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname. • public File[] listFiles(FilenameFilter filter) Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter. • public boolean mkdir() Creates the directory named by this abstract pathname. • public boolean mkdirs() Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories. 4/7/2018 28 The java.io.File Class //List of all files in D: with extention tgz import java.io.*; import java.util.*; public class DLister { public static void main(String[] args) { File path = new File("D:\\"); String[] list; list = path.list(new DirFilter(".tgz")); for(int i = 0; i < list.length; i++) System.out.println(list[i]); } } class DirFilter implements FilenameFilter { String afn; DirFilter(String afn) { this.afn = afn; } public boolean accept(File dir, String name) { String f = new File(name).getName(); return f.indexOf(afn) != -1; } } 4/7/2018 29 Exercise • public boolean deleteDir(String path) • public boolean find(String path, String filePattern) • public boolean find(String path, String pattern) 4/7/2018 30 The java.io.FileInputStream Class • A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment. • FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader. • public FileInputStream(File file) throws FileNotFoundException Creates a FileInputStream by opening a connection to an actual file, the file named by the File object file in the file system. A new FileDescriptor object is created to represent this file connection. • public FileInputStream(String name) throws FileNotFoundException Creates a FileInputStream by opening a connection to an actual file, the file named by the path name name in the file system. 4/7/2018 31 The java.io.FileInputStream Class • public int read() throws IOException – Reads a byte of data from this input stream. This method blocks if no input is yet available. – Returns: the next byte of data, or -1 if the end of the file is reached. • public int read(byte[] b) throws IOException • public int read(byte[] b, int off, int len) – Reads up to b.length bytes of data from this input stream into an array of bytes. This method blocks until some input is available. – Parameters: • b - the buffer into which the data is read. • off - the start offset of the data. • len - the maximum number of bytes read. – Returns: the total number of bytes read into the buffer, or -1 if there is no more data because the end of the file has been reached. 4/7/2018 32 The java.io.FileInputStream Class • public long skip(long n) throws IOException – Skips over and discards n bytes of data from the input stream. – Parameters: n - the num ... polymorphically through one of its subclasses. It has five write( ) methods as well as a flush( ) and a close( ) method: • protected Writer( ) • protected Writer(Object lock) • public abstract void write(char[] text, int offset, int length) • throws IOException • public void write(int c) throws IOException • public void write(char[] text) throws IOException • public void write(String s) throws IOException • public void write(String s, int offset, int length) throws • IOException • public abstract void flush( ) throws IOException • public abstract void close( ) throws IOException 4/7/2018 81 Writers char[] network = {'N', 'e', 't', 'w', 'o', 'r', 'k'}; w.write(network, 0, network.length); • The same task can be accomplished with these other methods as well: for (int i = 0; i < network.length; i++) w.write(network[i]); w.write("Network"); w.write("Network", 0, 7); • If it's using big-endian Unicode, then it will write these 14 bytes (shown here in hexadecimal) in this order: 00 4E 00 65 00 74 00 77 00 6F 00 72 00 6B • On the other hand, if w uses little-endian Unicode, this sequence of 14 bytes is written: 4E 00 65 00 74 00 77 00 6F 00 72 00 6B 00 • If uses Latin-1, UTF-8, or MacRoman, this sequence of seven bytes is written: 4E 65 74 77 6F 72 6B 4/7/2018 82 java.io.FileWriter • Convenience class for writing character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream. • public FileWriter(String fileName) throws IOException Constructs a FileWriter object given a file name. • public FileWriter(String fileName, boolean append) throws IOException Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written. • public FileWriter(File file) throws IOException Constructs a FileWriter object given a File object. • public FileWriter(File file, boolean append) throws IOException Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning. • Methods inherited from class java.io.OutputStreamWriter: close, flush, getEncoding, write 4/7/2018 83 Text Stream • Text stream cho phép user nhìn stream dưới dạng “đọc được” (readable) – InputStreamReader, OutputStreamWriter còn cung cấp thêm khả năng chuyển đổi stream reader/writer, khả năng làm việc với các bảng mã khác nhau – BufferedReader cung cấp cách đọc ra từng hàng từ một stream – BufferedWriter cung cấp cách thức ghi các chuỗi ra stream dưới dạng đọc được – PrintWriter cung cấp cách thức ghi các chuỗi, số nguyên, số thực, ... ra stream dưới dạng đọc được 4/7/2018 84 P r in tW r it er P rin tW rite r(arg0 : O utputS tream , auto F lus h : boo lean ) P rin tW rite r(arg0 : O utputS tream ) P rin tW rite r(arg0 : W rite r, au toF lus h : boo lean) P rin tW rite r(arg0 : W rite r) flus h() : vo id c los e() : vo id c hec k E rror() : boo lean s etE rror() : vo id w rite (arg0 : in t ) : vo id w rite (arg0 : c har[ ] , a rg1 : in t , a rg2 : in t ) : vo id w rite (arg0 : c har[ ] ) : vo id w rite (arg0 : S tring , a rg 1 : in t , a rg2 : in t ) : vo id w rite (arg0 : S tring) : vo id prin t(a rg0 : bo o lea n) : vo id prin t(a rg0 : c h ar) : vo id prin t(a rg0 : in t ) : vo id prin t(a rg0 : long) : vo id prin t(a rg0 : floa t) : vo id prin t(a rg0 : do ub le ) : vo id prin t(a rg0 : c h ar[ ] ) : vo id prin t(a rg0 : S tring) : vo id prin t(a rg0 : O b jec t ) : vo id prin t ln () : vo id prin t ln (arg0 : boo lean) : vo id prin t ln (arg0 : c har) : vo id prin t ln (arg0 : in t ) : vo id prin t ln (arg0 : long) : vo id prin t ln (arg0 : floa t) : vo id prin t ln (arg0 : doub le) : vo id prin t ln (arg0 : c har[ ] ) : vo id prin t ln (arg0 : S tring) : vo id prin t ln (arg0 : O b jec t) : vo id (fro m io ) 4/7/2018 85 BufferedReader BufferedReader(arg0 : Reader) BufferedReader(arg0 : Reader, arg1 : int) read() : int read(arg0 : char[], arg1 : int, arg2 : int) : int readLine(arg0 : boolean) : String readLine() : String skip(arg0 : long) : long ready() : boolean markSupported() : boolean mark(arg0 : int) : void reset() : void close() : void (from io) Reader (from io) BufferedReader 4/7/2018 86 BufferedWriter Writer (from io) BufferedWriter BufferedWriter(arg0 : Writer, arg1 : int) BufferedWriter(arg0 : Writer) flushBuffer() : void write(arg0 : int) : void write(arg0 : char[], arg1 : int, arg2 : int) : void write(arg0 : String, arg1 : int, arg2 : int) : void newLine() : void flush() : void close() : void (from io) 4/7/2018 87 java.io.OutputStreamWriter • public OutputStreamWriter(OutputStream out, String charsetName) throws UnsupportedEncodingException Create an OutputStreamWriter that uses the named charset. • Charset Description US-ASCII Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode character set ISO-8859-1 ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1 UTF-8 Eight-bit UCS Transformation Format UTF-16BE Sixteen-bit UCS Transformation Format, big-endian byte order UTF-16LE Sixteen-bit UCS Transformation Format, little-endian byte order UTF-16 Sixteen-bit UCS Transformation Format, byte order identified by an optional byte-order mark 4/7/2018 88 java.io.OutputStreamWriter • public OutputStreamWriter(OutputStream out) Create an OutputStreamWriter that uses the default character encoding. • public OutputStreamWriter(OutputStream out, CharsetEncoder enc) Create an OutputStreamWriter that uses the given charset encoder. • public String getEncoding() Return the name of the character encoding being used by this stream. • public void write(int c) throws IOException Write a single character. • public void write(char[] cbuf, int off, int len) throws IOException Write a portion of an array of characters. 4/7/2018 89 java.io.OutputStreamWriter • public void write(String str, int off, int len) throws IOException Write a portion of a string. • public void flush() throws IOException Flush the stream. • public void close() throws IOException Close the stream. 4/7/2018 90 OutputStreamWriter demo • import java.io.*; public class OutputStreamToWriterDemo{ public static void main(String args[]){ try{ OutputStream output = new FileOutputStream("utf8.txt"); // Create an OutputStreamWriter OutputStreamWriter writer = new OutputStreamWriter (output,"UTF-8"); // Write to file using a writer writer.write ("Phạm Văn Tính"); // Flush and close the writer, to ensure it is written writer.flush(); writer.close(); } catch (IOException ioe){ System.err.println ("I/O error : " + ioe); }}} 4/7/2018 91 java.io.InputStreamReader • An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset. The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted. • public InputStreamReader(InputStream in) – Create an InputStreamReader that uses the default charset. • public InputStreamReader(InputStream in, String charsetName) throws UnsupportedEncodingException – Create an InputStreamReader that uses the named charset. • public String getEncoding() – Return the name of the character encoding being used by this stream. 4/7/2018 92 java.io.InputStreamReader • public int read() throws IOException – Read a single character. • public int read(char[] cbuf, int offset, int length) throws IOException – Read characters into a portion of an array. • public boolean ready() throws IOException – Tell whether this stream is ready to be read. An InputStreamReader is ready if its input buffer is not empty, or if bytes are available to be read from the underlying byte stream. • public void close() throws IOException 4/7/2018 93 Charset Translation public class InputStreamReaderDemo { public static void main(String args[]){ try{ OutputStream output = new FileOutputStream("utf8_16.txt"); // Create an OutputStreamWriter OutputStreamWriter writer = new OutputStreamWriter (output, "UTF-16"); InputStream input = new FileInputStream("utf8.txt"); InputStreamReader reader = new InputStreamReader(input, "UTF-8"); char[] buff = new char[100]; // Write to file using a writer int rNumber = reader.read(buff); System.out.println("Number of char: "+rNumber); writer.write(buff,0,rNumber); // Flush and close the writer, to ensure it is written writer.flush(); writer.close(); reader.close(); } catch (IOException ioe){ System.err.println ("I/O error : " + ioe); }}} 4/7/2018 94 Complete example • Student List 4/7/2018 95 Object Streams • Using a fixed-length record format is a good choice if you need to store data of the same type. However, objects that you create in an object-oriented program are rarely all of the same type. • If we want to save files that contain this kind of information, we must first save the type of each object and then the data that defines the current state of the object. When we read this information back from a file, we must: – Read the object type; – Create a blank object of that type; – Fill it with the data that we stored in the file. • It is entirely possible (if very tedious) to do this by hand. However, Sun Microsystems developed a powerful mechanism called object serialization to read/write objects from/into the file. 4/7/2018 96 Storing Objects of Variable Type • To save object data, you first need to open an ObjectOutputStream object: • ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream( “student.dat")); • Now, to save an object, you simply use the writeObject method of the ObjectOutputStream class as in the following fragment: • //create objects Student hoa = new Employee(“Trần Thị Hoa", 1980, “CD02”); Student vinh = new Employee(“Lương Thế Vinh", 1981, “DH03”); • //Storing objects into stream out.writeObject(hoa); out.writeObject(vinh); 4/7/2018 97 Reading Objects back • First get an ObjectInputStream object • ObjectInputStream in = new ObjectInputStream(new FileInputStream("employee.dat")); • Then, retrieve the objects in the same order in which they were written, using the readObject method. • Student st1 = (Student)in.readObject(); Student st2 = (Student)in.readObject(); . • When reading back objects, you must carefully keep track of the number of objects that were saved, their order, and their types. Each call to readObject reads in another object of the type Object. You, therefore, will need to cast it to its correct type. 4/7/2018 98 Serializable interface • you need to make to any class that you want to save and restore in an object stream. The class must implement the Serializable interface: • class Employee implements Serializable { . . . } • The Serializable interface has no methods, so you don't need to change your classes in any way. • To make a class serializable, you do not need to do anything else. • Writing an array is done with a single operation: • Student[] stList = new Student[3]; . . . out.writeObject(stList); • Similarly, reading in the result is done with a single operation. However, we must apply a cast to the return value of the readObject method: • Student[] newStList = (Student[])in.readObject(); 4/7/2018 99 Student List using Object Streams public class SerialStudent implements Serializable{ private String name; private int age; private String cl; public SerialStudent(String n, int a, String c){ name = n; age = a; cl = c; } public String getName() { return name; } public int getAge() { return age; } public String getCl(){ return cl; } public String toString() { return getClass().getName() + "[Name=" + name + ",Age=" + age + ",Class=" + cl + "]"; } public void exportData(PrintWriter out){ out.println(name + "|" + age + "|" + cl); }} 4/7/2018 100 Student List using Object Streams public class SerialTest { public static void main(String[] args) { SerialStudent[] st = new SerialStudent[3]; st[0] = new SerialStudent("Phạm Thị Mỹ Hạnh", 20, "TC02"); st[1] = new SerialStudent("Trần Thị Hoa", 18, "CD02"); st[2] = new SerialStudent("Nguyễn Vãn Vệ", 19, "DH03"); try { // save all students records to the file studentemployee.dat ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("SerialStudent.dat")); out.writeObject(st); out.close(); // retrieve all records into a new array ObjectInputStream in = new ObjectInputStream(new FileInputStream("SerialStudent.dat")); try{ SerialStudent[] newSt = (SerialStudent[])in.readObject(); // print the newly read student records for (int i = 0; i < newSt.length; i++) System.out.println(newSt[i]); } catch (ClassNotFoundException e) {}; in.close(); .. 4/7/2018 101 java.io.ObjectOutputStream • ObjectOutputStream(OutputStream out) creates an ObjectOutputStream so that you can write objects to the specified OutputStream. • void writeObject(Object obj) writes the specified object to the ObjectOutputStream. This method saves the class of the object, the signature of the class, and the values of any non-static, non-transient field of the class and its superclasses. 4/7/2018 102 java.io.ObjectInputStream • ObjectInputStream(InputStream is) creates an ObjectInputStream to read back object information from the specified InputStream. • Object readObject() reads an object from the ObjectInputStream. In particular, this reads back the class of the object, the signature of the class, and the values of the nontransient and nonstatic fields of the class and all of its superclasses. It does deserializing to allow multiple object references to be recovered. 4/7/2018 103 InputStream Summary FileInputStream DataInputStream In p u tS tr ea m Int Float Double String Char Object R ea d er InputStreamReader FileReader char BufferedReader line CharSet ObjectInputStream Byte 4/7/2018 104 OutputStream Summary FileOutputStream DataOutputStream O u tp u tS tr e a m Int Float Double String Char String line W r it e r OutputStreamWriter er FileWriter char PrintWriter CharSet String line byte Object ObjectOutputStream 4/7/2018 105 Tóm tắt • Gói java.io chứa các lớp cho việc xuất nhập dữ liệu. • Các dòng xuất nhập được chia thành 2 loại: dòng văn bản, dòng byte vật lý. • Dòng văn bản xử lý dữ liệu theo từng ký tự 2 byte • Dòng byte vật lý xử lý dữ liệu theo từng byte. • Tác vụ nhập xuất có thể gây lỗi runtime nên cần throws IOException. • Khi lưu trữ dữ liệu vào dòng, cần chọn 1 định dạng lưu trữ trước để khi phải đọc ra sẽ đọc được đúng dữ liệu. 4/7/2018 106
File đính kèm:
- bai_giang_cong_nghe_java_chuong_8_java_inputoutput.pdf