Скачать презентацию Java Lecture 04 Input Output Programming Saint Скачать презентацию Java Lecture 04 Input Output Programming Saint

04_IO.pptx

  • Количество слайдов: 28

Java Lecture #04 Input / Output Programming Saint Petersburg, 2012 Java Lecture #04 Input / Output Programming Saint Petersburg, 2012

IO Overview § Пакет java. io § Ключевое понятие – поток – линейная последовательность IO Overview § Пакет java. io § Ключевое понятие – поток – линейная последовательность байт § Автоматически создаются 3 потока: § System. out § System. in § System. err 2

IO Overview § Пакет java. io § Ключевое понятие – поток – линейная последовательность IO Overview § Пакет java. io § Ключевое понятие – поток – линейная последовательность байт § Автоматически создаются 3 потока: § System. out § System. in § System. err 3

Streams § Input. Stream – поток для чтения данных § Output. Stream – поток Streams § Input. Stream – поток для чтения данных § Output. Stream – поток для записи данных 4

Kinds of Streams § § § Byte*Stream – работа с байтами Character*Stream – обработка Kinds of Streams § § § Byte*Stream – работа с байтами Character*Stream – обработка char’ов Buffered*Stream – буферный ввод/вывод Object*Stream – чтение/запись объектов Piped*Stream – чтение/запись на два потока File*Stream – работа с файлами 5

Input. Stream § § read() возвращает массив байт или единичный байт или -1, если Input. Stream § § read() возвращает массив байт или единичный байт или -1, если конец потока skip() пропускает заданное количество байт available() возвращает доступное для чтения число байт close() закрывает поток и освобождает ресурс § Некоторые классы поддерживают маркирование, проверить mark. Supported() § Пример: 1. 2. 3. 4. File. Input. Stream fis = new File. Input. Stream("myfile. dat"); Object. Input. Stream ois = new Object. Input. Stream(fis); Date date = (Date) ois. read. Object(); ois. close(); 6

Output. Stream § § § write() записывает массив байт или единичный байт flush() принуждает Output. Stream § § § write() записывает массив байт или единичный байт flush() принуждает записать существующий буфер close() закрывает поток и освобождает ресурс § Некоторые классы поддерживают маркирование, проверить mark. Supported() § Пример: 1. 2. 3. 4. File. Output. Stream fos = new File. Output. Stream("myfile. dat"); Object. Output. Stream oos = new Object. Output. Stream(fos); oos. write. Object(new Date()); oos. close(); 7

Pipes 1. 2. 3. 4. 5. 6. byte[] bb = new byte[20]; Piped. Input. Pipes 1. 2. 3. 4. 5. 6. byte[] bb = new byte[20]; Piped. Input. Stream pis = new Piped. Input. Stream(); Piped. Output. Stream pos = new Piped. Output. Stream(pis); pos. write(42); pis. read(bb); System. out. println(bb[0]); 8

Object. Stream 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. Object. Stream 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. File. Output. Stream fos = new File. Output. Stream("myfile. dat"); Object. Output. Stream oos = new Object. Output. Stream(fos); oos. write. Int(123456); oos. write. Object("Today"); oos. write. Object(new Date()); oos. close(); File. Input. Stream fis = new File. Input. Stream("myfile. dat"); Object. Input. Stream ois = new Object. Input. Stream(fis); int i = ois. read. Int(); String today = (String) ois. read. Object(); Date date = (Date) ois. read. Object(); ois. close(); 9

Reader / Writer § § нужны для работы с символьными потоками значительно повышают удобство Reader / Writer § § нужны для работы с символьными потоками значительно повышают удобство использования 10

Reader / Writer § read() возвращает символ или массив символов или -1, если достигнут Reader / Writer § read() возвращает символ или массив символов или -1, если достигнут конец § write() записывает символ или массив символов § Пример: 1. 2. 3. Buffered. Reader reader = new Buffered. Reader(new File. Reader("myfile. dat")); String s = reader. read. Line(); reader. close(); 11

What is Wrong? try { 2. Output. Stream file = new File. Output. Stream( What is Wrong? try { 2. Output. Stream file = new File. Output. Stream("myfile. dat"); 3. Output. Stream buffer = new Buffered. Output. Stream(file); 4. Object. Output output = new Object. Output. Stream(buffer); 5. output. write. Object(quarks); 6. } finally { 7. output. close(); 8. } 9. // program goes further 10. … 1. 12

What is Wrong? try { 2. Output. Stream file = new File. Output. Stream( What is Wrong? try { 2. Output. Stream file = new File. Output. Stream("myfile. dat"); 3. Output. Stream buffer = new Buffered. Output. Stream(file); 4. Object. Output output = new Object. Output. Stream(buffer); 5. output. write. Object(quarks); 6. } finally { 7. output. close(); 8. } 9. // program goes further 10. … 1. 13

What is Wrong? try { 2. Output. Stream file = new File. Output. Stream( What is Wrong? try { 2. Output. Stream file = new File. Output. Stream("myfile. dat"); 3. Output. Stream buffer = new Buffered. Output. Stream(file); 4. Object. Output output = new Object. Output. Stream(buffer); 5. output. write. Object(quarks); 6. } finally { 7. output. close(); 8. } 9. // program goes further 10. … 1. 14

Best Practices of java. io § 1. § § Потоки можно и нужно оборачивать Best Practices of java. io § 1. § § Потоки можно и нужно оборачивать друг в друга, например: Object. Output. Stream oos = new Object. Output. Stream(new Buffered. Output. Stream(new File. Output. Stream("myfile. dat"))); Потоки всегда надо закрывать Но не все - закрытия требует только последний созданный поток, так в примере выше, надо закрыть только oos. Закрытие должно происходить в блоке finally Лучше использовать буферизованные потоки – мгновенная обработка запросов на чтение/запись может снизить производительность 15

What will happen? 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. What will happen? 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. public class Main { public static void main(String[] args) { try { File. Output. Stream fos = new File. Output. Stream("myfile. dat"); Object. Output. Stream oos = new Object. Output. Stream(fos); oos. write. Object(new Dummy()); oos. close(); } catch (Exception e) { e. print. Stack. Trace(); } } } class Dummy { private String s = "123"; public String get. S() { return s; } } 16

What will happen? 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. What will happen? 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. public class Main { public static void main(String[] args) { try { File. Output. Stream fos = new File. Output. Stream("myfile. dat"); Object. Output. Stream oos = new Object. Output. Stream(fos); oos. write. Object(new Dummy()); oos. close(); } catch (Exception e) { e. print. Stack. Trace(); java. io. Not. Serializable. Exception: Dummy } } } class Dummy { private String s = "123"; public String get. S() { return s; } } 17

NIO & NIO 2 Overview § § § § NIO – New I/O NIO NIO & NIO 2 Overview § § § § NIO – New I/O NIO – J 2 SE 1. 4 NIO 2 – Java. SE 7 Пакет java. nio Изпользуется асинхронная модель передачи данных Buffers – типы для хранения данных; Charsets – различные кодировки Channels – аналоги потоков для быстрой записи или чтения данных Selectors – определяют неблокирующие возможности API 18

Buffer § основное средство хранения и обработки данных для каналов. 19 Buffer § основное средство хранения и обработки данных для каналов. 19

Scattering Reads and Gathering Writes 20 Scattering Reads and Gathering Writes 20

Selectors § основа неблокирующих сокетов 21 Selectors § основа неблокирующих сокетов 21

NIO Examples § 1. 2. 3. 4. 5. 6. 7. 8. Reading from a NIO Examples § 1. 2. 3. 4. 5. 6. 7. 8. Reading from a file: File. Input. Stream fin = new File. Input. Stream("myfile. dat"); File. Channel fc = fin. get. Channel(); Byte. Buffer buffer = Byte. Buffer. allocate(1024); fc. read(buffer); Writing to a file: File. Output. Stream fout = new File. Output. Stream("myfile. dat"); File. Channel fc = fout. get. Channel(); Byte. Buffer buffer = Byte. Buffer. allocate(1024); for (int i = 0; i < message. length; ++i) { buffer. put(message[i]); } buffer. flip(); fc. write(buffer); 22

IO vs NIO IO NIO Stream oriented Buffer oriented Blocking IO Non blocking IO IO vs NIO IO NIO Stream oriented Buffer oriented Blocking IO Non blocking IO Selectors 23

IO vs NIO – server design 24 IO vs NIO – server design 24

Sockets § § Клиентские и серверные сокеты обеспечивают обмен данными между процессами Количество доступных Sockets § § Клиентские и серверные сокеты обеспечивают обмен данными между процессами Количество доступных сокетов ограничевается возможностями операционной системы 25

Server. Socket § § 1. 2. 3. 4. 5. 6. 7. 8. 9. Синхронный Server. Socket § § 1. 2. 3. 4. 5. 6. 7. 8. 9. Синхронный ввод-вывод Модель thread per connection try { Server. Socket ss = new Server. Socket(9090); Socket s = ss. accept(); while (s. get. Input. Stream(). read() != -1) { System. out. println(s. get. Input. Stream(). read()); } } catch (IOException e) { // do something here } 26

Client. Socket § § 1. 2. 3. 4. 5. 6. 7. Синхронный ввод-вывод Модель Client. Socket § § 1. 2. 3. 4. 5. 6. 7. Синхронный ввод-вывод Модель thread per connection try { Socket s = new Socket("localhost", 9090); s. get. Output. Stream(). write(65535); s. close(); } catch (IOException e) { // do something here } 27

References § § § § § http: //docs. oracle. com/javase/tutorial/essential/io/ http: //docs. oracle. com/javase/7/docs/api/java/nio/package-summary. References § § § § § http: //docs. oracle. com/javase/tutorial/essential/io/ http: //docs. oracle. com/javase/7/docs/api/java/nio/package-summary. html http: //www. cs. brown. edu/courses/cs 161/papers/j-nio-ltr. pdf http: //today. java. net/pub/a/today/2007/02/13/architecture-of-highlyscalable-nio-server. html http: //tutorials. jenkov. com/java-nio/overview. html http: //onjava. com/pub/a/onjava/2002/10/02/javanio. html? page=1 http: //stackoverflow. com/questions/1605332/java-nio-filechannel-versusfileoutputstream-performance-usefulness http: //geekomatic. ch/2008/09/06/1220730740479. html http: //www. ibm. com/developerworks/library/j-zerocopy/ 28