Cours 9 Collections Collections o types de donnes
- Slides: 97
Cours 9
Collections
Collections o types de données n n n o interfaces implémentations algorithmes Interfaces: POO-L 3 H. Fauconnier 3
Collections: les interfaces Les collections sont des interfaces génériques o Collection<E>: add, remove size to. Array… n Set<E>: éléments sans duplication o n n o o Sorted. Set<E>: ensembles ordonnés List<E>: des listes éléments non ordonnés et avec duplication Queue<E>: files avec tête: peek, poll (défiler), offer (enfiler) Map<K, V>: association clés valeurs Sorted. Map<K, V> avec clés triées Certaines méthodes sont optionnelles (si elles ne sont pas implémentées Unsupported. Operation. Exception). En plus: o Iterator<E>: interface qui retourne successivement les éléments next(), has. Next(), remove() o List. Iterator<E>: itérateur pour des List, set(E) previous, add(E) POO-L 3 H. Fauconnier 4
Collection public interface Collection<E> extends Iterable<E> { // operations de base int size(); boolean is. Empty(); boolean contains(Object element); boolean add(E element); //optionnel boolean remove(Object element); //optionnel Iterator<E> iterator(); // operations des collections boolean contains. All(Collection<? > c); boolean add. All(Collection<? extends E> c); //optionnel boolean remove. All(Collection<? > c); //optionnel boolean retain. All(Collection<? > c); //optionnel void clear(); //optionnel // Array Object[] to. Array(); <T> T[] to. Array(T[] a); } POO-L 3 H. Fauconnier 5
Collection o o Les collections sont génériques Parcours: n On peut parcourir les éléments par « for » : for (Object o : collection) System. out. println(o); n Ou avec un Iterator: static void filter(Collection<? > c) { for (Iterator<? > it = c. iterator(); it. has. Next(); ) if (!cond(it. next())) it. remove(); } POO-L 3 H. Fauconnier 6
Collection o On peut convertir une collection en tableau n n o En tableaux de Object En tableaux d’objet du type paramètre de la collection Il existe aussi une classe Collections qui contient des méthodes statiques utiles POO-L 3 H. Fauconnier 7
Set o Interface pour contenir des objets différents n n o Opérations ensemblistes Sorted. Set pour des ensembles ordonnés Implémentations: n n n Hash. Set par hachage (preformances) Tree. Set arbre rouge-noir Linked. Hash. Set ordonnés par ordre d’insertion POO-L 3 H. Fauconnier 8
Set public interface Set<E> extends Collection<E> { // Basic operations int size(); boolean is. Empty(); boolean contains(Object element); boolean add(E element); //optional boolean remove(Object element); //optional Iterator<E> iterator(); // Bulk operations boolean contains. All(Collection<? > c); // sous-ensemble boolean add. All(Collection<? extends E> c); //optionnel- union boolean remove. All(Collection<? > c); //optionnel- différence boolean retain. All(Collection<? > c); //optionnel- intersection void clear(); //optionnel // Array Operations Object[] to. Array(); <T> T[] to. Array(T[] a); } POO-L 3 H. Fauconnier 9
Exemple: public static void cherche. Doublons(String. . . st){ Set<String> s = new Hash. Set<String>(); for (String a : st) if (!s. add(a)) System. out. println("Doublon: " + a); System. out. println("il y a "+s. size() + " mots différents: " + s); } public static void cherche. Doublonsbis(String st[]){ Set<String> s=new Hash. Set<String>(); Set<String> sdup=new Hash. Set<String>(); for(String a : st) if (!s. add(a)) sdup. add(a); s. remove. All(sdup); System. out. println("Mots uniques: " + s); System. out. println("Mots dupliqués: " + sdup); } POO-L 3 H. Fauconnier 10
Lists o En plus de Collection: n n n o Accès par position de l ’élément Recherche qui retourne la position de l’élément Sous-liste entre deux positions Implémentations: n n Array. List Linked. List POO-L 3 H. Fauconnier 11
List public interface List<E> extends Collection<E> { // Positional access E get(int index); E set(int index, E element); //optional boolean add(E element); //optional void add(int index, E element); //optional E remove(int index); //optional boolean add. All(int index, Collection<? extends E> c); //optional // Search int index. Of(Object o); int last. Index. Of(Object o); // Iteration List. Iterator<E> list. Iterator(); List. Iterator<E> list. Iterator(int index); // Range-view List<E> sub. List(int from, int to); } POO-L 3 H. Fauconnier 12
Itérateur pour listes public interface List. Iterator<E> extends Iterator<E> { boolean has. Next(); E next(); boolean has. Previous(); E previous(); int next. Index(); int previous. Index(); void remove(); //optional void set(E e); //optional void add(E e); //optional } POO-L 3 H. Fauconnier 13
Exemple public static <E> void swap(List<E> a, int i, int j) { E tmp = a. get(i); a. set(i, a. get(j)); a. set(j, tmp); } public static void melange(List<? > list, Random rnd) { for (int i = list. size(); i > 1; i--) swap(list, i - 1, rnd. next. Int(i)); } POO-L 3 H. Fauconnier 14
Suite… public static <E> List<E> une. Main(List<E> deck, int n) { int deck. Size = deck. size(); List<E> hand. View = deck. sub. List(deck. Size - n, deck. Size); List<E> hand = new Array. List<E>(hand. View); hand. View. clear(); return hand; } public static void distribuer(int n. Mains, int n. Cartes) { String[] couleurs = new String[]{"pique", "coeur", "carreau", "trèfle"}; String[] rank = new String[] {"as", "2", "3", "4", "5", "6", "7", "8", "9", "10", "valet", "dame", "roi"}; List<String> deck = new Array. List<String>(); for (int i = 0; i < couleurs. length; i++) for (int j = 0; j < rank. length; j++) deck. add(rank[j] + " de " + couleurs[i]); melange(deck, new Random()); for (int i=0; i < n. Mains; i++) System. out. println(une. Main(deck, n. Cartes)); } POO-L 3 H. Fauconnier 15
Map o Map associe des clés à des valeurs n n Association injective: à une clé correspond exactement une valeur. Trois implémentations, comme pour set o o o n Hash. Map, Tree. Map, Linked. Hash. Map Remplace Hash POO-L 3 H. Fauconnier 16
Map public interface Map<K, V> { // Basic operations V put(K key, V value); V get(Object key); V remove(Object key); boolean contains. Key(Object key); boolean contains. Value(Object value); int size(); boolean is. Empty(); // Bulk operations void put. All(Map<? extends K, ? extends V> m); void clear(); // Collection Views public Set<K> key. Set(); public Collection<V> values(); public Set<Map. Entry<K, V>> entry. Set(); // Interface for entry. Set elements public interface Entry { K get. Key(); V get. Value(); V set. Value(V value); } } POO-L 3 H. Fauconnier 17
Exemples public static void map. Freq(String. . . t) { Map<String, Integer> m = new Hash. Map<String, Integer>(); for (String a : t) { Integer freq = m. get(a); m. put(a, (freq == null) ? 1 : freq + 1); } System. out. println("Il y a: " + m. size() + " mots différents: n"+m); } // ordre arbitraire POO-L 3 H. Fauconnier 18
Exemples public static void map. Freq(String. . . t) { Map<String, Integer> m = new Tree. Map<String, Integer>(); for (String a : t) { Integer freq = m. get(a); m. put(a, (freq == null) ? 1 : freq + 1); } System. out. println("Il y a: " + m. size() + " mots différents: n"+m); } // ordre arbitraire POO-L 3 H. Fauconnier 19
Exemples public static void map. Freq(String. . . t) { Map<String, Integer> m = new Linked. Hash. Map<String, Integer>(); for (String a : t) { Integer freq = m. get(a); m. put(a, (freq == null) ? 1 : freq + 1); } System. out. println("Il y a: " + m. size() + " mots différents: n"+m); } // ordre arbitraire POO-L 3 H. Fauconnier 20
Queue o Pour représenter une file (en principe FIFO): n n o Insertion: offer -add Extraction: poll - remove Pour voir: peek –element (retourne une valeur - exception Priority. Queue implémentation pour une file à priorité POO-L 3 H. Fauconnier 21
Interface Queue public interface Queue<E> extends Collection<E> { E element(); boolean offer(E e); E peek(); E poll(); E remove(); } POO-L 3 H. Fauconnier 22
Exemple public static void compteur(int n) throws Interrupted. Exception { Queue<Integer> queue = new Linked. List<Integer>(); for (int i = n; i >= 0; i--) queue. add(i); while (!queue. is. Empty()) { System. out. println(queue. remove()); Thread. sleep(1000); } } POO-L 3 H. Fauconnier 23
Exemple static <E> List<E> heap. Sort(Collection<E> c) { Queue<E> queue = new Priority. Queue<E>(c); List<E> result = new Array. List<E>(); while (!queue. is. Empty()) result. add(queue. remove()); return result; } POO-L 3 H. Fauconnier 24
Des implémentations o o o o Hash. Set<E>: implémentation de. Set comme table de hachage. Recherche/ ajout suppression en temps constant Tree. Set<E>: Sorted. Set comme arbre binaire équilibré O(log(n)) Array. List<E>: liste implémentée par des tableaux à taille variable accès en O(1) ajout et suppression en. O(n-i) (i position considérée) Linked. List<E>: liste doublement chaînée implémente List et Queue accès en O(i) Hash. Map<K, V>: implémentation de Map pas table de hachage ajout suppression et recherche en O(1) Tree. Map<K, V>: implémentation de Sorted. Map à partir d'arbres équilibrésajout, suppression et recherche en O(log(n)) Weak. Hash. Map<K, V>: implémentation de Map par table de hachage Priority. Queue<E>: tas à priorité. POO-L 3 H. Fauconnier 25
Comparaisons o Interface Comparable<T> contient la méthode n n o public int compare. To(T e) "ordre naturel" Interface Comparator<T> contient la méthode n I/O package public int compare(T o 1, T o 2) POO-L 3 H. Fauconnier 26
Quelques autres packages o System méthodes static pour le système: n n n I/O package entrée-sorties standard manipulation des propriétés systèmes utilitaires "Runtime" exit(), gc() … POO-L 3 H. Fauconnier 27
Runtime, Process o o Runtime permet de créer des processus pour exécuter des commande: exec Process retourné par un exec méthodes n n n I/O package destroy() exit. Value() get. Input. Stream() get. Output. Stream() get. Error. Stream() POO-L 3 H. Fauconnier 28
Exemple o exécuter une commande (du système local) n n I/O package associer l'entrée de la commande sur System. in associer la sortie sur System. out. POO-L 3 H. Fauconnier 29
Exemple class plug. Together extends Thread { Input. Stream from; Output. Stream to; plug. Together(Output. Stream to, Input. Stream from ) { this. from = from; this. to = to; } public void run() { byte b; try { while ((b= (byte) from. read()) != -1) to. write(b); } catch (IOException e) { System. out. println(e); } finally { try { to. close(); from. close(); } catch (IOException e) { System. out. println(e); } } } I/O package POO-L 3 H. Fauconnier } 30
Exemple suite public class Main { public static Process user. Prog(String cmd) throws IOException { Process proc = Runtime. get. Runtime(). exec(cmd); Thread thread 1 = new plug. Together(proc. get. Output. Stream(), System. in); Thread thread 2 = new plug. Together(System. out, proc. get. Input. Stream()); Thread thread 3 = new plug. Together(System. err, proc. get. Error. Stream()); thread 1. start(); thread 2. start(); thread 3. start(); try {proc. wait. For(); } catch (Interrupted. Exception e) {} return proc; } public static void main(String args[]) throws IOException { String cmd = args[0]; System. out. println("Execution de: "+cmd); Process proc = user. Prog(cmd); } } I/O package POO-L 3 H. Fauconnier 31
Java Swing
Principes de base o Des composants graphiques (exemple: JFrame, JButton …) o o Hiérarchie de classes Des événements et les actions à effectuer (exemple presser un bouton) o (Et d'autres choses…)
Principes o o o Définir les composants (instance de classes) Les placer à la main (layout Manager) dans un JPanel ou un content pane ou en utilisant des outils comme eclipse ou netbeans Définir les actions associées aux événements (Listener) et les associer aux composants graphiques
Principes o o o Dans une interface graphique, le programme réagit aux interactions avec l'utilisateur Les interactions génèrent des événements Le programme est dirigé par les événements (event-driven)
Afficher… o Pour pouvoir être affiché, il faut que le composant soit dans un top-level conteneur: (JFrame, JDialog et JApplet) o Hiérarchie des composants: arbre racine top-level
Exemple o Correspond à la hiérarchie
Le code import java. awt. *; import javax. swing. *; public class Top. Level { /** * Affiche une fenêtre JFrame top level * avec une barre de menu JMenu. Bar verte * et un JLabel jaune */ private static void afficher. Ma. Fenetre() { //créer la Jframe //créer la JMenu. Bar //créer le Jlabel // mettre le JMenu. Bar et le Jlable dans la Jframe //afficher la Jframe } }
Le code //Creer la JFrame frame = new JFrame("Top. Level. Demo"); frame. set. Default. Close. Operation(JFrame. EXIT_ON_CLOSE); //Créer la JMenu. Bar green. Menu. Bar = new JMenu. Bar(); green. Menu. Bar. set. Opaque(true); green. Menu. Bar. set. Background(new Color(0, 200, 0)); green. Menu. Bar. set. Preferred. Size(new Dimension(200, 20)); //Créer le JLabel yellow. Label = new JLabel(); yellow. Label. set. Opaque(true); yellow. Label. set. Background(new Color(250, 0)); yellow. Label. set. Preferred. Size(new Dimension(200, 180)); //mettre la Jmenu. Bar et position le JLabel frame. set. JMenu. Bar(green. Menu. Bar); frame. get. Content. Pane(). add(yellow. Label, Border. Layout. CENTER); //afficher. . . frame. pack(); frame. set. Visible(true);
Et le main public class Top. Level {//afficher. Ma. Fenetre() public static void main(String[] args) { javax. swing. Swing. Utilities. invoke. Later(new Runnable() { public void run() { afficher. Ma. Fenetre(); } }
Evénements: principes o Dans un système d'interface graphique: n n Quand l'utilisateur presse un bouton, un "événement" est posté et va dans une boucle d'événements Les événements dans la boucle d'événements sont transmis aux applications qui se sont enregistrées pour écouter.
Evénements o Chaque composant génère des événements: n Presser un JButton génère un Action. Event (système d'interface graphique) o n Un event listener (implémente Action. Listener) o o n Cet Action. Event contient des infos (quel bouton, position de la souris, modificateurs…) définit une méthode action. Performed S'enregistre auprès du bouton add. Action. Listener Quand le bouton est "clické", l'action. Performed sera exécuté (avec l'Action. Event comme paramètre)
Exemples Buttons
Un exemple o Un bouton qui réagit
Le code: o o o Un JButton Un JLabel Implementer Action. Listener n o action. Perfomed définit ce qui se passe quand le bouton est cliqué Placer le bouton et le label
Code: import java. awt. *; import javax. swing. JFrame; import javax. swing. JPanel; import javax. swing. JButton; import javax. swing. Jcomponent; import java. awt. Toolkit; import java. awt. Border. Layout; import java. awt. event. Action. Listener; import java. awt. event. Action. Event; import javax. swing. JLabel; public class Un. Bouton extends Jpanel implements Action. Listener { JButton bouton; String contenu="Rien Reçu"; JLabel label=new JLabel(contenu); int cmp=0; public Un. Bouton() { //…} public void action. Performed(Action. Event e) {//…} private static void ma. Fenetre(){//…} public static void main(String[] args) {//…} }
Code public Un. Bouton() { super(new Border. Layout()); bouton = new JButton("Click"); bouton. set. Preferred. Size(new Dimension(200, 80)); add(bouton, Border. Layout. NORTH); label = new JLabel(contenu); label. set. Preferred. Size(new Dimension(200, 80)); add(label, Border. Layout. SOUTH); bouton. add. Action. Listener(this); } public void action. Performed(Action. Event e) { Toolkit. get. Default. Toolkit(). beep(); label. set. Text("clické "+ (++cmp)+ " fois"); }
Code private static void ma. Fenetre() { JFrame frame = new JFrame("Un. Bouton"); frame. set. Default. Close. Operation(JFrame. EXIT_ON_CLOSE); JComponent new. Content. Pane = new Un. Bouton(); new. Content. Pane. set. Opaque(true); frame. set. Content. Pane(new. Content. Pane); frame. pack(); frame. set. Visible(true); } public static void main(String[] args) { //Formule magique javax. swing. Swing. Utilities. invoke. Later(new Runnable() { public void run() { ma. Fenetre(); } }); }
Variante public class Un. Bouton. Bis extends JPanel { //… bouton. add. Action. Listener(new Action. Listener() { public void action. Performed(Action. Event e) { Toolkit. get. Default. Toolkit(). beep(); label. set. Text("clické " + (++cmp) + " fois"); } }); } //… }
Hiérarchie des classes… POO-L 3 H. Fauconnier 50
Un exemple o Un traceur de fonctions n Une interface graphique swing
Organisation o Graphe. Swing contient un. Graphe. Panel extension de Jpanel n Graphe. Panel méthode paint. Component qui affiche le graphe de la fonction o o Graphe est la classe contenant le gaphe et définissant une méthode draw pour l'affichage Cette méthode appelle tracer de la classe abstraite Traceur n Fonction. Traceur étend Traceur POO-L 3 H. Fauconnier 53
Le main public static void main(String[] args) { new Graphe. Swing(un. Graphe()); } public static Graphe un. Graphe() { Plot. Settings p = new Plot. Settings(-2, 2, -1, 1); p. set. Plot. Color(Color. RED); p. set. Grid. Spacing. X(0. 5); p. set. Grid. Spacing. Y(0. 5); p. set. Title("Une parabole et une sinusoide"); Graphe graphe = new Graphe(p); graphe. functions. add(new Parabole()); graphe. functions. add(new Fonction. Traceur() { public double get. Y(double x) { return Math. sin(x); } public String get. Name() { return "Sin(x)"; } }); return graphe; } POO-L 3 H. Fauconnier 54
Composants o Modèle Vue Contrôleur
Préliminaires… o Lightweight et heavyweight composants n Dépendent ou non du système d’interface graphique o o n Lightweight écrit en Java et dessinés dans un heavyweight composant- indépendant de la plateforme Les heavyweight composants s’adressent directement à l’interface graphique du système (certaines caractéristiques dépendent du look and feel).
Look and feel o Look and feel: Possibilité de choisir l’apparence de l’interface graphique. UIManager gère l’apparence de l’interface
Multithreading o Attention au « modèle, contrôleur, vue » en cas de multithreading: n n Tous les événements de dessin de l’interface graphiques sont dans une unique file d’event-dispatching dans une seule thread. La mise à jour du modèle doit se faire tout de suite après l’événement de visualisation dans cette thread.
Plus précisément o o o Swing prend en charge la gestion des composants qui sont dessinés en code Java (lightweight) Les composants AWT sont eux liés aux composants natifs (heavyweight) Swing dessine le composants dans un canevas AWT et utilise le traitement des événements de AWT
Suite Les threads o Main application thread o Toolkit thread o Event dispatcher thread o Toutes Les opérations d'affichage ont lieu dans une seule thread l'EDT
Principes o o Une tâche longue ne doit pas être exécutée dans l'EDT Un composant Swing doit s'exécuter dans l'EDT
Exemple public void action. Performed(Action. Event e){ try { Thread. sleep(4000); } catch (Interrupted. Exception e) { } } Provoque une interruption de l'affichage pendant 4 secondes
Une solution public void action. Performed(Action. Event e){ try{ Swing. Utilities. invoke. Later(new. Runnable( { public void run() { //opération longue } }); } catch (Interrupted. Exception ie) {} catch (Invocation. Target. Exception ite) {} } }
Le main o Normalement la création d'une fenêtre ne devrait avoir lieu que dans l'EDT: public static void main(String[] args) { //Formule magique javax. swing. Swing. Utilities. invoke. Later(new Runnable() { public void run() {ma. Fenetre(); } }); } invoke. Later crée une nouvelle thread qui poste la thread crée dans l'EDT
Attendre le résultat: try { Swing. Utilities. invoke. And. Wait(new Runnable() { public void run() { show(); } }); } catch (Interrupted. Exception ie) { } catch (Invocation. Target. Exception ite) { }
Chapitre IX Entrées-sorties
Principes généraux o entrées sorties n n o o streams dans java. io channels dans java. nio ("n" pour non-blocking) streams: séquences de données ordonnées avec une source (stream d'entrée) ou une destination (stream de sortie) channels et buffer. Buffer contient les données et le channel correspond à des connections I/O package POO-L 3 H. Fauconnier 67
Streams o Deux grandes sortes de Stream n n o character Streams contiennet des caractères UTF-16 byte Streams contiennent des octets Character versus byte n n n I/O package imput ou output stream pour les byte reader, writer pour les character deux hiérarchies qui se correspondent POO-L 3 H. Fauconnier 68
Hiérarchie o java. io. Input. Stream (implements java. io. Closeable) n n n java. io. Byte. Array. Input. Stream java. io. File. Input. Stream java. io. Filter. Input. Stream o o n n I/O package java. io. Buffered. Input. Stream java. io. Data. Input. Stream (implements java. io. Data. Input) java. io. Line. Number. Input. Stream java. io. Pushback. Input. Stream java. io. Object. Input. Stream (implements java. io. Object. Input, java. io. Object. Stream. Constants) java. io. Piped. Input. Stream java. io. Sequence. Input. Stream java. io. String. Buffer. Input. Stream POO-L 3 H. Fauconnier 69
Hiérarchie o java. io. Output. Stream (implements java. io. Closeable, java. io. Flushable) n n n java. io. Byte. Array. Output. Stream java. io. File. Output. Stream java. io. Filter. Output. Stream o o o n n I/O package java. io. Buffered. Output. Stream java. io. Data. Output. Stream (implements java. io. Data. Output) java. io. Print. Stream (implements java. lang. Appendable, java. io. Closeable) java. io. Object. Output. Stream (implements java. io. Object. Output, java. io. Object. Stream. Constants) java. io. Piped. Output. Stream POO-L 3 H. Fauconnier 70
Hiérachie… o java. io. Reader (implements java. io. Closeable, java. lang. Readable) n java. io. Buffered. Reader o n n java. io. Char. Array. Reader java. io. Filter. Reader o n n I/O package java. io. Pushback. Reader java. io. Input. Stream. Reader o n java. io. Line. Number. Reader java. io. File. Reader java. io. Piped. Reader java. io. String. Reader POO-L 3 H. Fauconnier 71
Hiérarchie n java. io. Writer (implements java. lang. Appendable, java. io. Closeable, java. io. Flushable) o o java. io. Buffered. Writer java. io. Char. Array. Writer java. io. Filter. Writer java. io. Output. Stream. Writer n o o o I/O package java. io. File. Writer java. io. Piped. Writer java. io. Print. Writer java. io. String. Writer POO-L 3 H. Fauconnier 72
Streams d'octets o Class Input. Stream (toutes ces méthodes peuvent lancer IOEXception) n abstract int read() lit un octet n int read (byte[] b) lit et écrit dans b, (le nombre d'octets lus dépend de b et est retourné n int read(byte[] b, int off, int len) n long skip(long n) n int available() n d'octets pouvant être lus n void mark(int readlimit) et void reset() pose d'une marque et retour à la marque n voidclose() I/O package POO-L 3 H. Fauconnier 73
Stream d'octets o Output. Stream (toutes ces méthodes peuvent lancer IOEXception) n n n I/O package abstract void write(int b) écrit un octet void write(byte[] b) void write(byte[] b, int off, int len) voidclose() voidflush() POO-L 3 H. Fauconnier 74
Exemples public static int compte. IS(String st) throws IOException{ Input. Stream in; int n=0; if (st==null)in=System. in; else in= new File. Input. Stream(st); for(; in. read() != -1; n++); return n; } I/O package POO-L 3 H. Fauconnier 75
Exemples public static void tr. OS(String f, char from, char to){ int b; Output. Stream out=null; try{ if(f==null) out=System. out; else out=new File. Output. Stream(f); while((b= System. in. read())!=-1) out. write(b==from? to: b); out. flush(); out. close(); }catch(IOException ex){ ex. print. Stack. Trace(); } } I/O package POO-L 3 H. Fauconnier 76
Reader-Writer o Reader et Writer sont les deux classes abstraites pour les streams de caractères: n I/O package le read de Input. Stream retourne un byte comme octet de poids faible d'un int alors que le read de Reader retourne un char à partir de 2 octets de poids faible d'un int POO-L 3 H. Fauconnier 77
Reader o essentiellement les mêmes méthodes que pour Input. Stream: n n n n n I/O package int read() int read(char[] cbuf) abstract int read(char[] cbuf, int off, int len) int read(Char. Buffer target) boolean ready() si prêt à lire voidreset() voidmark(int read. Ahead. Limit) booleanmark. Supported() longskip(long n) POO-L 3 H. Fauconnier 78
Writer o similaire à Output. Stream mais avec des caractères au lieu d'octets. n n n I/O package void write(char[] cbuf) abstract void write(char[] cbuf, int off, int len) void write(int c) void write(String str, int off, int len) Writer append(char c) Writer append(Char. Sequence csq, int start, int end) abstract void close() abstract void flush() POO-L 3 H. Fauconnier 79
Exemples public static int compte. R(String st) throws IOException{ Reader in; int n=0; if (st==null) in=new Input. Stream. Reader(System. in); else in= new File. Reader(st); for(; in. read() != -1; n++); return n; } I/O package POO-L 3 H. Fauconnier 80
Exemples public static void tr. Wr(String f, char from, char to){ int b; Writer out=null; try { if(f==null) out= new Output. Stream. Writer(System. out); else out=new File. Writer(f); while((b= System. in. read())!=-1) out. write(b==from? to: b); out. flush(); out. close(); }catch(IOException e){System. out. println(e); } } I/O package POO-L 3 H. Fauconnier 81
Remarques o o o les streams standard System. in et System. out sont des streams d'octets Input. Stream. Reader permet de passer de Input. Stream à Reader System. in et System. out sont des Print. Stream (obsolète à remplacer par la version caractère Print. Writer) I/O package POO-L 3 H. Fauconnier 82
Input. Stream. Reader et Output. Stream. Writer o o conversion entre caractères et octets, la conversion est donnée par un charset Constructeurs: n n n n I/O package Input. Stream. Reader(Input. Stream in) Input. Stream. Reader(Input. Stream in, Charset cs) Input. Stream. Reader(Input. Stream in, String charset. Name) Output. Stream. Writer(Output. Stream out, Charset cs) Output. Stream. Writer(Output. Stream out, Charset. Encoder enc) Output. Stream. Writer(Output. Stream out, String charset. Name) POO-L 3 H. Fauconnier 83
Autres classes o o o File. Input. Stream File. Output. Stream File. Reader File. Writer Ces classes permettent d'associer une stream à un fichier donné par son nom (String) par un objet File ou un objet File. Descriptor (un mode append peut être défini pour les ecritures) I/O package POO-L 3 H. Fauconnier 84
Quelques autres classes o Les filtres n n o Buffered n n o Filter. Input. Stream Filter. Output. Stream Filter. Reader Filter. Writer Buffered. Input. Stream Buffered. Output. Stream Buffered. Reader Buffered. Writer Tubes n n I/O package Piped. Input. Stream Piped. Output. Stream Piped. Reader Piped. Writer POO-L 3 H. Fauconnier 85
Exemple d'un filtre class conversion. Maj extends Filter. Reader{ public conversion. Maj(Reader in){ super(in); } public int read() throws IOException{ int c=super. read(); return(c==-1? c: Character. to. Upper. Case((char)c)); } public int read(char[] buf, int offset, int count)throws IOException{ int nread=super. read(buf, offset, count); int last=offset+nread; for(int i=offset; i<last; i++) buf[i] = Character. to. Upper. Case(buf[i]); return nread; } } I/O package POO-L 3 H. Fauconnier 86
Exemple suite: String. Reader source=new String. Reader("ma chaîne"); Filter. Reader filtre=new conversion. Maj(source); int c; try{ while((c=filtre. read())!= -1) System. out. print((char)c); }catch(IOException e){ e. print. Stack. Trace(System. err); } I/O package POO-L 3 H. Fauconnier 87
Pipe (tube) o Un tube associe une entrée et un sortie: on lit à une extrémité et on écrit à l'autre. I/O package POO-L 3 H. Fauconnier 88
Exemple pipe class Pipe. Exemple extends Thread{ private Writer out; private Reader in; public Pipe. Exemple(Writer out, Reader in){ this. out=out; this. in=in; } public void run(){ int c; try{ while ((c=in. read())!=-1){ out. write(Character. to. Upper. Case((char)c)); } }finally{out. close(); } }catch(IOException e){e. print. Stack. Trace(System. err); } } } I/O package POO-L 3 H. Fauconnier 89
Suite Piped. Writer out 1=new Piped. Writer(); Piped. Reader in 1=new Piped. Reader(out 1); Piped. Writer out 2=new Piped. Writer(); Piped. Reader in 2=new Piped. Reader(out 2); Pipe. Exemple pipe=new Pipe. Exemple(out 1, in 2); pipe. start(); try{ for(char c='a'; c<='z'; c++) { out 2. write(c); System. out. print((char)(in 1. read())); } }finally { out 2. close(); } I/O package POO-L 3 H. Fauconnier 90
Byte. Array, String… o java. io. Input. Stream (implements java. io. Closeable) n java. io. Byte. Array. Input. Stream java. io. String. Buffer. Input. Stream n java. io. Byte. Array. Output. Stream n o o java. io. Output. Stream (implements java. io. Closeable, java. io. Flushable) java. io. Reader (implements java. io. Closeable, java. lang. Readable) n n o java. io. Char. Array. Reader java. io. String. Reader java. io. Writer (implements java. lang. Appendable, java. io. Closeable, java. io. Flushable) n n I/O package java. io. Char. Array. Writer java. io. String. Writer POO-L 3 H. Fauconnier 91
Print Streams o o java. io. Print. Stream (implements java. lang. Appendable, java. io. Closeable) java. io. Print. Writer n I/O package méthode println() POO-L 3 H. Fauconnier 92
Streams pour les données o o Data. Input: interface pour lire des bytes d'une stream binaire et les transformer en données java de type primitif Data. Output: interface pour convertir des valeurs de type primitif en stream binaire. I/O package POO-L 3 H. Fauconnier 93
Sérialisation o sauvegarder des objets java en flot d'octets: o objet vers byte: sérialisation n byte vers objet: désérialisation java. io. Object. Input. Stream (implements java. io. Object. Input, java. io. Object. Stream. Constants) n o I/O package POO-L 3 H. Fauconnier 94
Sauver des objets o o la serialisation-désérialisation doit permettre de sauvegarder et restituer des objets. sauver et restituer des objets n'est pas si simple. Pourquoi? interface serializable (alternative XML) I/O package POO-L 3 H. Fauconnier 95
Manipuler des fichiers… o java. io. File (implements java. lang. Comparable<T>, java. io. Serializable) I/O package POO-L 3 H. Fauconnier 96
nio o entrée sorties de haute performance avec contrôle sur les buffers. I/O package POO-L 3 H. Fauconnier 97
- Tu nous a donné
- Le pain de ta vie
- Zone cours
- La tectonique des plaques - cours
- Réponse
- Stratégie marketing indifférencié exemple
- Ancetre de l'aspirateur
- Tableur excel
- Fiche technique d'un cours
- Cours de communication professionnelle ppt
- Crise biologique
- Cours interactif
- Ihm
- Dr surrel
- Croupe topographie
- Cours vhdl ppt
- Cours sainte marie de hann
- L'équilibre alimentaire cours ifsi
- Cours sur la rémunération en grh
- Cem cours
- Les loi de thermodynamique
- Nombre chromatique graphe cours
- Antiseptique et désinfectant cours
- Sadt
- Syllabus exemple
- Business plan notion
- Cours présentation assistée par ordinateur
- Plan de développement des ressources humaines
- Pharmacodynamie ifsi
- Parkour meaning in french
- Taux de glycémie à jeun
- Methode croc appel
- Introduction aux relations internationales s1
- Canal de fallope
- Les helminthes cours
- Capteur et conditionneur cours
- Cours cod 1 pompier
- Perte de charge hectometrique
- Filtrage numérique cours
- Pum emg
- Audio numérique cours
- Cours anthropologie infirmier
- Dialyse péritonéale
- Cours sur les trames
- Cours sévigné abidjan
- Esxi memory ballooning
- Sensation et perception en psychologie
- Gestion de projet cours résumé
- Cours hydrogéologie master
- Dendrologie cours
- Cours de narration
- Www.cned.fr 360
- Cours modulo
- Cio de cenon
- Drain pleural surveillance infirmière
- Au cour de la semaine
- Relation entre ka et kb
- Les suites du cours
- Lignes de transmission cours
- Univ 3.constantine medecine
- Riahla cours
- Ses versailles cours inversés
- Cours mimo
- Vih cours ifsi
- Hydrologie cours
- Gestion internationale des ressources humaines cours
- Faculté de médecine constantine cours
- Cours introductif
- Les parties du texte narratif
- Westga courseden
- Traitement automatique des langues
- Cours pl sql
- Psychologie expérimentale - cours
- Data mining cours
- Politique commerciale cours
- Distance interréticulaire hexagonal
- Mpd base de données
- Tuan loc
- Guillaume villemaud
- Intégrale impropre cours
- Vision par ordinateur cours
- Cours stmg
- Cours technologie charcuterie
- Compteur asynchrone modulo 8 bascule jk
- Stratégie corporate cours
- Cours emarketing
- Carte perceptuelle marketing
- Cytosquelette cours
- Cours traitement de texte open office
- Trnsys simulation studio
- Transistor bipolaire
- Les anticoagulants cours ifsi
- E marketing planning process
- Kraljic matrise
- Denavit-hartenberg exercices corrigés
- Communication médiatique cours
- Cours dynatrace
- Grisaille diffuse