Bài giảng Lập trình hướng đối tượng: Các luồng vào / ra - Nguyễn Việt Hà

pdf 45 trang phuongnguyen 3850
Bạn đang xem 20 trang mẫu của tài liệu "Bài giảng Lập trình hướng đối tượng: Các luồng vào / ra - Nguyễn Việt Hà", để tải tài liệu gốc về máy bạn click vào nút DOWNLOAD ở trên

Tài liệu đính kèm:

  • pdfbai_giang_lap_trinh_huong_doi_tuong_cac_luong_vao_ra_nguyen.pdf

Nội dung text: Bài giảng Lập trình hướng đối tượng: Các luồng vào / ra - Nguyễn Việt Hà

  1. Các luồng vào / ra
  2. Nội dung „ Khái niệm về luồng dữ liệu „ Luồng và tệp „ Lớp File „ Truy cập tệp tuần tự „ Truy cập tệp ngẫu nhiên NguyễnViệtHà Các luồng vào ra 2
  3. Tài liệu tham khảo „ Thinking in Java, chapter 12 „ Java how to program, chapter 17 NguyễnViệtHà Các luồng vào ra 3
  4. Luồng dữ liệu (data streams) „ Chương trình Java nhận và gửi dữ liệu thông qua các đối tượng là các thực thể thuộc một kiểu luồng dữ liệu nào đó „ Luồng (stream) là một dòng dữ liệu đếntừ một nguồn (source) hoặc đi đếnmột đích (sink) „ Nguồnvàđíchcóthể là tệp (file), bộ nhớ, mộttiến trình (process), hay thiếtbị (bàn phím, màn hình, ) NguyễnViệtHà Các luồng vào ra 4
  5. Luồng byte và char „ Luồng byte: thao tác theo đơn vị byte InputStream OutputStream „ Luồng char: thao tác vớikýtự Reader Writer NguyễnViệtHà Các luồng vào ra 5
  6. InputStream „ int read() „ int read(byte buf[]) „ int read(byte buf[], int offset, int length) „ void close() NguyễnViệtHà Các luồng vào ra 6
  7. OutputStream „ int write(int c) „ int write(byte buf[]) „ int write(byte buf[], int offset, int length) „ void close() „ void flush() NguyễnViệtHà Các luồng vào ra 7
  8. Reader „ int read() „ int read(char buf[]) „ int read(char buf[], int offset, int length) „ void close() NguyễnViệtHà Các luồng vào ra 8
  9. Writer „ int write(int c) „ int write(char buf[]) „ int write(char buf[], int offset, int length) „ void close() „ void flush() NguyễnViệtHà Các luồng vào ra 9
  10. Phả hệ của InputStream NguyễnViệtHà Các luồng vào ra 10
  11. Phả hệ của OutputStream NguyễnViệtHà Các luồng vào ra 11
  12. Phả hệ của Reader NguyễnViệtHà Các luồng vào ra 12
  13. Phả hệ củaWriter NguyễnViệtHà Các luồng vào ra 13
  14. Đốitượng vào / ra „ Để nhậphoặcxuấtdữ liệu, chúng ta phải tạora đốitượng vào hoặcra „ Đốitượng vào hoặcra thuộckiểuluồng tương ứng và phải đượcgắnvớimột nguồndữ liệuhoặcmột đích tiêu thụ dữ liệu NguyễnViệtHà Các luồng vào ra 14
  15. Sử dụng bộđệm „ Bộđệmlàmộtkỹ thuật để tăng tính hiệuquả của thao tác vào / ra đọc và ghi dữ liệu theo khối giảm số lần thao tác với thiết bị „ Thay vì ghi trực tiếp tới thiết bị thì chương trình ghi lên bộ đệm khi bộ đệm đầy thì dữ liệu được ghi ra thiết bị theo khối có thể ghi vào thời điểm bất kỳ bằng phương thức flush() „ Thay vì đọc trực tiếp từ thiết bị thì chương trình đọc từ bộ đệm khi bộ đệm rỗng thì dữ liệu được đọc theo khối từ thiết bị NguyễnViệtHà Các luồng vào ra 15
  16. Nhậpxuất qua thiếtbị chuẩn Console I/O „ System.out cho phép in ra luồng ra chuẩn là đối tượng của lớp PrintStream „ System.err cho phép in ra luồng thông báo lỗichuẩn là đối tượng của lớp PrintStream „ System.in cho phép đọcvàotừ thiếtbị vào chuẩn là đối tượng củalớp InputStream NguyễnViệtHà Các luồng vào ra 16
  17. Đọcdữ liệutừ luồng vào chuẩn „ System.in không sử dụng đượctrựctiếp „ Chúng ta muốn đọc một dòng ký tự 1. tạo đối tượng luồng ký tự (InputStreamReader) 2. tạo đối tượng luồng có bộ đệm (BufferedReader) NguyễnViệtHà Các luồng vào ra 17
  18. Ví dụ: InputStreamReader reader = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(reader); String s; try { s = in.readLine(); } catch (IOException e) { } NguyễnViệtHà Các luồng vào ra 18
  19. Lớp File „ Một trong các nguồn và đích dữ liệu thông thường là tệp „ Lớp File cung cấpcácchức năng cơ bản để thao tác vớitệp nằm trong gói java.io tạotệp, mở tệp, các thông tin về tệpvàthư mục NguyễnViệtHà Các luồng vào ra 19
  20. Tạo đốitượng File „ File myFile; „ myFile = new File(“data.txt”); „ myFile = new File(“myDocs”, “data.txt”); „ Thư mụccũng đượccoi như là mộttệp File myDir = new File(“myDocs”); File myFile = new File(myDir, “data.txt”); có phương thức riêng để thao tác với thư mục NguyễnViệtHà Các luồng vào ra 20
  21. Các phương thức „ Tên tệp String getName() String getPath() String getAbsolutePath() String getParent() boolean renameTo(File newName) „ Kiểmtra tệp boolean exists() boolean canWrite() boolean canRead() boolean isFile() boolean isDirectory() boolean isAbsolute() NguyễnViệtHà Các luồng vào ra 21
  22. Các phương thức(2) „ Nhận thông tin long lastModified() long length() boolean delete() „ Thư mục boolean mkdir() String[] list() NguyễnViệtHà Các luồng vào ra 22
  23. Thao tác với tệpký tự „ Đọctừ tệp FileReader: đọc ký tự từ tệp BufferedReader: đọc có bộ đệm (đọc từng dòng readLine()) „ Ghi ra tệp FileWriter: ghi ký tự ra tệp PrintWriter: ghi theo dòng (print() và println()) NguyễnViệtHà Các luồng vào ra 23
  24. Ví dụ: Đọcvàotừ tệp File file = new File(”data.txt”); FileReader reader = new FileReader(file); BufferedReader in = new BufferedReader(reader); String s; try { s = in.readLine(); } catch (IOException e) { } NguyễnViệtHà Các luồng vào ra 24
  25. Ví dụ: Đọc vào (cont.) File file = new File(”data.txt”); FileReader reader = new FileReader(file); BufferedReader in = new BufferedReader(reader); Abc abc = new Abc(); abc.read(in); abc.doSomething(); NguyễnViệtHà Các luồng vào ra 25
  26. Ví dụ: Đọc vào (cont.) class Abc { public void read(BufferedReader in) { String s; try { s = in.readLine(); } catch (IOException e) { } } public void doSomething() { } } NguyễnViệtHà Các luồng vào ra 26
  27. Ví dụ: Ghi ra tệp File file = new File(”data.out”); FileWriter writer = new FileWriter(file); PrintWriter out = new PrintWriter(writer); String s = ”Hello”; try { out.println(s); out.close(); } catch (IOException e) { } NguyễnViệtHà Các luồng vào ra 27
  28. Ví dụ: Ghi ra (cont.) class Abc { public void write(PrintStream out) { try { out.println(s); out.close(); } catch (IOException e) { } } } NguyễnViệtHà Các luồng vào ra 28
  29. Ví dụ: Ghi ra (cont.) class Abc { public String write() { String buf; buf += return buf; } } NguyễnViệtHà Các luồng vào ra 29
  30. Ví dụ: File copy import java.io.*; public class CopyFile { public static void main(String args[]) { try { FileReader src = new FileReader(args[0]); BufferedReader in = new BufferedReader(src); FileWriter des = new FileWriter(args[1]); PrintWriter out = new PrintWriter(des); String s; s = in.readLine(); while (s != null) { out.println(s); s = in.readLine(); } in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } } NguyễnViệtHà Các luồng vào ra 30
  31. Ví dụ: File copy (2) import java.io.*; public class CopyFile2 { public static void main(String args[]) { try { FileReader src = new FileReader(args[0]); FileWriter des = new FileWriter(args[1]); char buf[] = new char[128]; int charsRead; charsRead = src.read(buf); while (charsRead != -1) { des.write(buf, 0, charsRead); charsRead = src.read(buf); } src.close(); des.close(); } catch (IOException e) { e.printStackTrace(); } } } NguyễnViệtHà Các luồng vào ra 31
  32. Thao tác với tệp dữ liệu (tuần tự) „ Đọcdữ liệu FileInputStream: đọc dữ liệu từ tệp DataInputStream: đọc dữ liệu kiểu nguyên thủy ObjectInputStream: đọc đối tượng „ Ghi dữ liệu FileOutputStream: ghi dữ liệura tệp DataOutputStream: ghi dữ liệukiểu nguyên thủy ObjectOutputStream: ghi đốitượng NguyễnViệtHà Các luồng vào ra 32
  33. DataInputStream/DataOutputStream „ DataInputStream: đọccácdữ liệu nguyên thủy readBoolean, readByte, readChar, readShort, readInt, readLong, readFloat, readDouble „ DataOutputStream: ghi các dữ liệu nguyên thủy writeBoolean, writeByte, writeChar, writeShort, writeInt, writeLong, writeFloat, writeDouble NguyễnViệtHà Các luồng vào ra 33
  34. Ghi dữ liệu nguyên thủy (tuầntự) import java.io.*; public class TestDataOutputStream { public static void main(String args[]) { int a[] = {2, 3, 5, 7, 11}; try { FileOutputStream fout = new FileOutputStream(args[0]); DataOutputStream dout = new DataOutputStream(fout); for (int i=0; i<a.length; i++) dout.writeInt(a[i]); dout.close(); } catch (IOException e) { e.printStackTrace(); } } } NguyễnViệtHà Các luồng vào ra 34
  35. Đọcdữ liệu nguyên thủy (tuầntự) import java.io.*; public class TestDataInputStream { public static void main(String args[]) { try { FileInputStream fin = new FileInputStream(args[0]); DataInputStream din = new DataInputStream(fin); while (true) { System.out.println(din.readInt()); } } catch (EOFException e) { } catch (IOException e) { e.printStackTrace(); } } } NguyễnViệtHà Các luồng vào ra 35
  36. Đốitượng “tuầntự” „ Một đốitượng có thểđượclưu trong bộ nhớ tại nhiềuvùngnhớ khác nhau các thuộc tính không phải là kiểu nguyên thủy „ Đối tượng muốn ghi / đọc được phải thuộc lớp có cài đặt giao diện Serializable đây là giao diện nhãn, không có phương thức NguyễnViệtHà Các luồng vào ra 36
  37. import java.io.Serializable; class Record implements Serializable { private String name; private float score; public Record(String s, float sc) { name = s; score = sc; } public String toString() { return "Name: " + name + ", score: " + score; } } NguyễnViệtHà Các luồng vào ra 37
  38. import java.io.*; public class TestObjectOutputStream { public static void main(String args[]) { Record r[] = { new Record("john", 5.0F), new Record("mary", 5.5F), new Record("bob", 4.5F) }; try { FileOutputStream fout = new FileOutputStream(args[0]); ObjectOutputStream out = new ObjectOutputStream(fout); for (int i=0; i<r.length; i++) out.writeObject(r[i]); out.close(); } catch (IOException e) { e.printStackTrace(); } } } NguyễnViệtHà Các luồng vào ra 38
  39. import java.io.*; public class TestObjectInputStream { public static void main(String args[]) { Record r; try { FileInputStream fin = new FileInputStream(args[0]); ObjectInputStream in = new ObjectInputStream(fin); while (true) { r = (Record) in.readObject(); System.out.println(r); } } catch (EOFException e) { System.out.println("No more records"); } catch (ClassNotFoundException e) { System.out.println("Unable to create object"); } catch (IOException e) { e.printStackTrace(); } } } NguyễnViệtHà Các luồng vào ra 39
  40. Lớp RandomAccessFile „ Là mộtlớp độclập(kế thừatrựctiếptừ Object) „ Đảmnhậnviệc đọc và ghi dữ liệu ngẫu nhiên cài đặt các giao diện DataInput và DataOutput „ Kích thước bản ghi phải cố định NguyễnViệtHà Các luồng vào ra 40
  41. import java.io.*; public class WriteRandomFile { public static void main(String args[]) { int a[] = { 2, 3, 5, 7, 11, 13 }; try { File fout = new File(args[0]); RandomAccessFile out; out = new RandomAccessFile(fout, "rw"); for (int i=0; i<a.length; i++) out.writeInt(a[i]); out.close(); } catch (IOException e) { e.printStackTrace(); } } } NguyễnViệtHà Các luồng vào ra 41
  42. import java.io.*; public class ReadRandomFile { public static void main(String args[]) { try { File fin = new File(args[0]); RandomAccessFile in = new RandomAccessFile(fin, "r"); int recordNum = (int) (in.length() / 4); for (int i=recordNum-1; i>=0; i ) { in.seek(i*4); System.out.println(in.readInt()); } } catch (IOException e) { e.printStackTrace(); } } } NguyễnViệtHà Các luồng vào ra 42
  43. Lớp Scanner „ Là lớp mới hỗ trợ nhập dữ liệu, kế thừa trực tiếp từ Object (từ Java 1.5) „ Khởi tạo với đối số là đối tượng vào (luồng, tệp, xâu ký tự) „ Có các phương thức hỗ trợ nhập trực tiếp nextType, hasNextType NguyễnViệtHà Các luồng vào ra 43
  44. Scanner sc = new Scanner(System.in); int i = sc.nextInt(); Scanner sc; sc = new Scanner(new File("myNumbers")); while (sc.hasNextLong()) { long aLong = sc.nextLong(); } String str = ”2 3 5 7”; Scanner sc = new Scanner(str); while (sc.hasNextInt()) { System.out.println(sc.nextInt()); } NguyễnViệtHà Các luồng vào ra 44
  45. class Abc { public void read(Scanner sc) { } public void doSomething() { } } NguyễnViệtHà Các luồng vào ra 45