•Flux de données •Lecture/Ecriture Fichiers - lacl.fr · import java.io.IOException; ouverture...

19
1 •Flux de données •Lecture/Ecriture Fichiers

Transcript of •Flux de données •Lecture/Ecriture Fichiers - lacl.fr · import java.io.IOException; ouverture...

1

•Flux de données•Lecture/Ecriture Fichiers

2

Un flux de données est un objet qui représente une suite d’octets d’un programme pour une certaine destination ou issus d’une source pour un programme

flux d’entrée (input stream): données vers le programmeflux de sortie (output stream): données issues du programme

•flux d’entrée à partir du clavier System.in

Scanner keyboard = new Scanner(System.in);

•flux de sortie vers l’écran ou un fichierSystem.out System.out.println("Output stream");

3

•Classe PrintWriter est un flux de sortie (output stream)pour écrire sur un fichier de texte méthodes print, println similaires de la classe System.out

import java.io.PrintWriter;import java.io.FileOutputStream;import java.io.FileNotFoundException;

PrintWriter fluxSortie;fluxSortie = new PrintWriter(

new FileOutputStream(fichierNom));

Constructeur FileOutputStream prend comme argument un objet Stringqui est le nom du fichier de Constructeur PrintWriter prend un objet anonyme de classe FileOutputStream

4

On obtient un objet PrintWriter connecté au fichier texte fichierNom

Ouverture du fichier fichierNom• si le fichier existe le contenu est écrasé• si le fichier n’existe pas un nouveau fichier est crée

Concaténer:fluxSortie =new PrintWriter(

new FileOutputStream(fichierNom,true));

Ecriture avec print, println: fluxSortie.println(“une chaine de caracteres” );

5

import java.io.PrintWriter;import java.io.FileOutputStream;import java.io.FileNotFoundException;

public class TextFileOutputDemo{ public static void main(String[] args) { PrintWriter fluxSortie = null; try { fluxSortie = new PrintWriter(new FileOutputStream("fichier.txt")); } catch(FileNotFoundException e) { System.out.println("Erreur d’ouverture fichier.txt."); System.exit(0); }

System.out.println("Ecriture sur fichier");

fluxSortie.println(" Premiere ligne du fichier "); fluxSortie.println(" Deuxiemeligne du fichier.");

fluxSortie.close( );

System.out.println("Fin du programme."); }}

6

Classe Scanner pour lire à partir d’un fichier texte

import java.util.Scanner;import java.io.FileInputStream;import java.io.FileNotFoundException;

Lecture à partir du fichier standard d’entrée (clavier):Scanner fluxEntree =new Scanner(System.in);Lecture à partir du fichier fluxEntree:Scanner fluxEntree = new Scanner(new FileInputStream(fichierNom));

Les mêmes méthodes que la classe Scanner fluxEntree.nextInt(), fluxEntree.nextLine(), fluxEntree.nextDouble(), fluxEntree.nextLong()....

fluxEntree.hasNextLine(), fluxEntree.hasNextInt() ... retourne un boolean

7

import java.util.Scanner;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.PrintWriter;import java.io.FileOutputStream;

public class DemoIO{ public static void main(String[] args) { Scanner fluxEntree = null; PrintWriter fluxSortie = null;

try { fluxEntree = new Scanner(new FileInputStream("original.txt")); fluxSortie= new PrintWriter( new FileOutputStream("numerote.txt")); } catch(FileNotFoundException e) { System.out.println("Erreur ouverture fichier."); System.exit(0); } String ligne = null; int no = 0; while (fluxEntree.hasNextLine( )) { ligne = fluxEntree.nextLine( ); no++; fluxSortie.println(no + " " + ligne); }

fluxEntree.close( ); fluxSortie.close( ); }}

8

Classe BufferedReader pour lire à partir d’un fichier

méthodes: read and readLine

import java.io.BufferedReader;import java.io.FileReader;import java.io.FileNotFoundException;import java.io.IOException;

ouverture du fichier texte:BufferedReader lectObj;lectObj= new BufferedReader(newFileReader(FichierNom));

readline lire une chaine de charactères (null si EOF)read lire un char (-1 si EOF)

retourne un entier il faut convertirchar next = (char)(lectObj.read());readline, read peuvent lancer IOException

9

. readline retourne null si EOF

. read retourne -1 si EOF

Lecture des nombres:1) readline(),2) Integer.parseInt(), Double.parseDouble(), ...

10

import java.io.BufferedReader;import java.io.FileReader;import java.io.FileNotFoundException;import java.io.IOException;

public class TextFileInputDemo{ public static void main(String[] args) { try {BufferedReader fluxEntree= new BufferedReader(new FileReader("donnee.txt"));

String ligne = fluxEntree.readLine( ); System.out.println(" Premiere ligne:"); System.out.println(ligne); ligne = fluxEntree.readLine( ); System.out.println(" Seconde ligne:"); System.out.println(ligne); fluxEntree.close( ); } catch(FileNotFoundException e) { System.out.println(" Fichier donnee nexiste pas"); System.out.println("ou erreur ouverture");} catch(IOException e) { System.out.println("Erreur lecture donnee.txt.");} }}

11

Classe File est une classe pour les noms de fichiers

File fichierObj =new File( “donnees“);

if ( fichierObj.exists()) System.out.println(“fichier existe“);if (fichierObj.canRead())System.out.println(“pas lisible“);

12

Copyright © 2008 Pearson Addison-Wesley. All rights reserved

13

Copyright © 2008 Pearson Addison-Wesley. All rights reserved

14Copyright © 2008 Pearson Addison-Wesley. All rights reserved

15Copyright © 2008 Pearson Addison-Wesley. All rights reserved

16

Fichiers Binaires Java sont portableslectureObjectInputStream

import java.io.ObjectInputStream;import java.io.FileInputStream;import java.io.IOException;

ObjectInputStream fluxObj= new ObjectInputStream(new FileInputStream(fichierNom));

– constructeur FileInputStream peut lancer FileNotFoundException– constructeur ObjectInputStream peut lancer IOException

–méthodes :readInt, readDouble, readChar, readBoolean readUTF pour String

-il faut fermer le flux après lecture: close -lance EOFException si c’est la fin du fichier

17

– writeObject pour écrire un objet –readObject pour lire un objet– uneClasse unObjet=(uneClasse) fluxObj.readObject();–les objets doivent appartenir à une classe qui implémente l’interface Serializable cette interface n’a aucune méthode, aucune constante si la classe a des objets comme attributs, il faut que ces classes soient aussi Serializable

- il vaut mieux sauvegarder les objets d’une même classe

18

import java.io.ObjectOutputStream;import java.io.FileOutputStream;import java.io.IOException;

public class BinaryOutputDemo{ public static void main(String[] args) { try { ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream( "donne.dat"));

int i; for (i = 0; i < 5; i++) out.writeInt(i);

System.out.println(" on ecrit dans donne.dat."); out.close( ); } catch(IOException e) { System.out.println("Probleme fichier sortie."); } }}

19

import java.io.ObjectInputStream;import java.io.FileInputStream;import java.io.IOException;import java.io.FileNotFoundException;

public class BinaryInputDemo{ public static void main(String[] args) {try { ObjectInputStream in= new ObjectInputStream(new FileInputStream(" donne.dat"));

int n1 = in.readInt( ); int n2 = in.readInt( );

System.out.println("ce qu’on a lus :"); System.out.println(n1); System.out.println(n2); in.close( ); } catch(FileNotFoundException e) { System.out.println( "Erreur donne.dat.");} catch(IOException e) {System.out.println("Problemes donnees dans donne.dat.");} System.out.println( " Fin du programme"); }}