Accueil
Java Standard Edition
Java EE 5
Visual Basic .Net 2005
Visual C++ .Net 2005
Visual C# .Net 2005
Cours ASP .Net 2.0
Postgresql
Linux
Visual Studio 2008
ASP 3.0 Classique
Cours Javascript - DOM - DHTML
Cours Ajax
VBA
Assembleur
Perl
Membres
L'auteur du site
Nouveautés sur le site
Contacts
Plan du site
Exécution d'un programme
Les archives Jar
Les classes abstraites
Les interfaces
Les tableaux
La généricité
Les énumérations
Les classes internes
Classes anonymes et internes locales
Les threads: généralités
Les threads(2): synchronisation
E/S(1):InputStream et OutputStream
E/S(2):FileInputStream et FileOutputStream
E/S(3):Reader et Writer
E/S(4):FilterInputStream et FilterOutputStream
E/S(5):Les filtres d'octets: PrintStream
E/S(6):Les filtres d'octets: DataInputStream et DataOutputStream
E/S(7):Les filtres d'octets: BufferedInputStream et BufferedOutputStream
E/S(8):Flux de caractères: PrintWriter
E/S(9):Flux de caractères: FilterReader et FilterWriter
E/S(10):Flux de caractères: InputStreamReader, OutputStreamWriter, StreamDecoder, StreamEncoder
E/S(11):Flux de caractères: BufferedReader et BufferedWriter
E/S(12):Flux de caractères: FileReader et FileWriter
La classe String (java.lang)
Les collections: L'interface Collection(java.lang)
Les collections(2): L'interface List(java.util)
Les collections(3): AbstractCollection(java.util)
Les collections(4): AbstractList(java.util)
Les collections(5): Vector(java.util)
Les collections(6): L'interface Map(java.util)
Les collections(7): AbstractMap(java.util)
Les collections(8): HashMap(java.util)
La bibliothèque Swing en Java
Les bases de données en Java
JDBC ( Java Database Connectivity )
Les interfaces graphiques
Les fichiers de configuration en Java
INSTALLATION JAVA EE 5, JRE 6, ECLIPSE, TOMCAT, ETC SOUS LINUX
INSTALLATION JAVA EE 5, JRE 6, ECLIPSE, TOMCAT, ETC SOUS WINDOWS
Les applications Web en java
Les filtres Java (javax.servlet.Filter)
I Généralités
I.1 Le formulaire principal
I.2 Les objets créés par Visual
I.3 Les variables références
I.4 Le garbage collector
II Créer évènements
II.1 Rappel évènements
II.2 Procédure à suivre
II.2.1 Créer son EventArgs
II.2.2 Créer EmetEvent
II.2.3 Déclarations autres
I Généralités
I.1 Applications winforms
I.2 Applications MFC
I.3 Objets managés ou pas
I.4 Objets non managés
I.5 Objets managés - handle
I.6 Le top-level ^
II Créer évènements
II.1 Rappel évènements
II.2 Procédure à suivre
II.2.1 Créer son EventArgs
II.2.2 Créer EmetEvent
II.2.3 Déclarations autres
I Généralités
I.1 Puissant et Accessible
I.2 Créer ses classes
II Créer évènements
II.1 Rappel évènements
II.2 Procédure à suivre
III Les services Windows
IV Le .net remoting
V Communication Tcp avec TcpClient et TcpListener
II.2.1 Créer son EventArgs
II.2.2 Créer EmetEvent
II.2.3 Déclarations autres
I Généralités
I.1 Un EDI formidable
I.2 Inclure C# ou VB
I.3 L'objet Response
I.4 Les évènements
II ASP .net et les bdd
II.1 Essayer plusieurs fois la requête
I 2.1 Fichiers distincts
I.2.2 Avec la balise script
I.2.3 Inclure réellement
I.2.4 Avec Response.Write()
I.3.1 La méthode Response.Redirect()
I.4.1 Résoudre problème post
Installation Postgre Linux
Cours Postgresql
Le Shell Unix( Linux, Ubuntu)
Les scripts C-Shell
Programmation système Unix
Reseau Linux
Les iptables
Windows Presentation Foundation(WPF)
Le Framework 3.0
Windows Workflow Foundation(WF)
ASP 3.0 Classique
Cours Javascript - DOM - DHTML
Chat Ajax
VBA Excel 2003
Assembleur
Perl
Inscription
Liste membres
Livre d'or
Forum
Accueil
>
Java Standard Edition
>
E/S(8):Flux de caractères: PrintWriter
____________________________________________________________________________________________________
Connexion
Les entrées-sorties(8) - Les classes héritant de Reader et Writer: PrintWriter
Sommaire :
I) Généralités
II) Définition de PrintWriter (java.io)
III) Les contructeurs de PrintWriter
Jusqu'à maintenant, nous avons vu les classes Reader et Writer(java.io), qui sont les classes de base pour les flux de caractères.
Nous avons vu également, à l'occasion d'articles sur les flux d'octets, deux classes héritant de Writer:
OutputStreamWriter (java.io)
StreamEncoder (sun.nio.cs)
I) Généralités
PrintWriter implémente la classe abstraite Writer. Un flux de caractères n'existe pas directement en réalité, par exemple, quelque soit le système d'exploitation, un fichier est formé d'octets. Un caractère est toujours un codage vers quelques octets( deux octets notamment pour Unicode).
Ceci veut dire qu'un flux de caractères est créé à partir d'un flux d'octets, ce n'est pas un concept natif des systèmes d'exploitation. Cependant, une classe de base pour les fichiers de caractères existe, car pour nous, êtres humains, c'est un concept de base, au même titre que les flux d'octets. Ce qui n'empêche pas d'ajouter des constructeurs pour permettre de le construire à partir d'un flux d'octets!
C'est le cas de PrintWriter, qui possède un constructeur avec un argument de type OutputStream, ou encore un constructeur de type File, qui va créer un objet FileOutputStream à partir de cet objet File( FileOutputStream qu'il transformera d'ailleurs en OutputStreamWriter, puis en BufferedWriter).
II) Définition de PrintWriter (java.io)
Le code source de PrintWriter est simple.
PrintWriter a les mêmes fonctionnalités que PrintStream, à la différence que PrintStream est du type FilterOutputStream, donc OutputStream. PrintStream a donc la philosophie des flux d'octets, et possède donc les méthodes d'écriture d'octets bruts, comme write (int byte), méthodes que ne possède bien sûr pas PrintWriter.
PrintWriter possède toutes les méthodes print et println de PrintStream, qui sont d'ailleurs implémentées de la même manière. Il possède aussi l'autoflush, mais les conditions de mise en route de l'autoflush sont différentes de PrintStream: l'autoflush a lieu uniquement après println. Une différence aussi, c'est que le séparateur de ligne utilisé est celui de la plateforme, et non forcément le caractère newline.
Comme PrintStream, les méthodes de PrintWriter ne déclenchent jamais d'IOException. C'est à l'utilisateur d'appeler la méthode checkerror(), qui retourne true ou false s'il y a eu erreur ou pas.
La seule différence d'implémentation est que PrintWriter possède un attribut privé out, représentant le flux sous-jacent, mais qui est de type Writer, et pas de type OutputStream. On remarque au passage que PrintWriter est en réalité un filtre, bien que n'héritant pas d'une classe conceptuelle de filtre(ce qui n'empêche pas d'être un filtre!).
III) Les contructeurs de PrintWriter
Regardons les constructeurs de PrintWriter:
/** * Creates a new PrintWriter, without automatic line flushing. * * @param out A character-output stream */ public PrintWriter (Writer out) { this(out, false); }
Dans le cas où on possède déjà un writer. PrintWriter est dans ce cas pleinement similaire à un filtre.
/** * Creates a new PrintWriter. * * @param out A character-output stream * @param autoFlush A boolean; if true, the
println
, *
printf
, or
format
methods will * flush the output buffer */ public PrintWriter(Writer out, boolean autoFlush) { super(out); this.out = out; this.autoFlush = autoFlush; lineSeparator = (String) java.security.AccessController.doPrivileged( new sun.security.action.GetPropertyAction("line.separator")); } /** * Creates a new PrintWriter, without automatic line flushing, from an * existing OutputStream. This convenience constructor creates the * necessary intermediate OutputStreamWriter, which will convert characters * into bytes using the default character encoding. * * @param out An output stream * * @see java.io.OutputStreamWriter#OutputStreamWriter(java.io.OutputStream) */ public PrintWriter(OutputStream out) { this(out, false); }
Ici on crée un PrintWriter depuis un OutputStream, ce qui nous rappelle qu'un flux de caractère n'existe pas nativement sur les ordinateurs. C'est donc bien un flux d'octets qui donne en réalité naissance à un flux de caractères.
/** * Creates a new PrintWriter from an existing OutputStream. This * convenience constructor creates the necessary intermediate * OutputStreamWriter, which will convert characters into bytes using the * default character encoding. * * @param out An output stream * @param autoFlush A boolean; if true, the
println
, *
printf
, or
format
methods will * flush the output buffer * * @see java.io.OutputStreamWriter#OutputStreamWriter(java.io.OutputStream) */ public PrintWriter(OutputStream out, boolean autoFlush) { this(new BufferedWriter(new OutputStreamWriter(out)), autoFlush); // save print stream for error propagation if (out instanceof java.io.PrintStream) { psOut = (PrintStream) out; } }
Ce constructeur transforme le OutputStream d'abord en OutputStreamWriter, qui est un Writer.
Ce pont OutputStreamWriter, qui permet de passer du monde des flux d'octets, au monde des flux de caractères, est en réalité un filtre, car il travaille avec un flux(d'octets) sous-jacent.
Cet OutputStreamWriter permet lui-même de créer un BufferedWriter. Enfin on appelle le constructeur de PrintWriter qui prend un Writer en argument.
Au final, remarquons que pour passer du OuputStream d'origine au Writer(BufferedWriter ici), on est passé par le bridge OutputStreamWriter.
/** * Creates a new PrintWriter, without automatic line flushing, with the * specified file name. This convenience constructor creates the necessary * intermediate {@link java.io.OutputStreamWriter OutputStreamWriter}, * which will encode characters using the {@linkplain * java.nio.charset.Charset#defaultCharset() default charset} for this * instance of the Java virtual machine. * * @param fileName * The name of the file to use as the destination of this writer. * If the file exists then it will be truncated to zero size; * otherwise, a new file will be created. The output will be * written to the file and is buffered. * * @throws FileNotFoundException * If the given string does not denote an existing, writable * regular file and a new regular file of that name cannot be * created, or if some other error occurs while opening or * creating the file * * @throws SecurityException * If a security manager is present and {@link * SecurityManager#checkWrite checkWrite(fileName)} denies write * access to the file * * @since 1.5 */ public PrintWriter(String fileName) throws FileNotFoundException { this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName))), false); }
Même chose que ci-dessus, avec une étape en plus au départ: on crée un FileOutputStream à partir du nom de fichier d'abord( c'est donc un OutputStream). Puis on fait comme précédemment: création d'un OutputStreamWriter à partir de là, puis d'un BufferedWriter, et enfin appel au constructeur qui demande un Writer.
/** * Creates a new PrintWriter, without automatic line flushing, with the * specified file name and charset. This convenience constructor creates * the necessary intermediate {@link java.io.OutputStreamWriter * OutputStreamWriter}, which will encode characters using the provided * charset. * * @param fileName * The name of the file to use as the destination of this writer. * If the file exists then it will be truncated to zero size; * otherwise, a new file will be created. The output will be * written to the file and is buffered. * * @param csn * The name of a supported {@linkplain java.nio.charset.Charset * charset} * * @throws FileNotFoundException * If the given string does not denote an existing, writable * regular file and a new regular file of that name cannot be * created, or if some other error occurs while opening or * creating the file * * @throws SecurityException * If a security manager is present and {@link * SecurityManager#checkWrite checkWrite(fileName)} denies write * access to the file * * @throws UnsupportedEncodingException * If the named charset is not supported * * @since 1.5 */ public PrintWriter(String fileName, String csn) throws FileNotFoundException, UnsupportedEncodingException { this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), csn)), false); }
La nouveauté ici par rapport à ci-dessus est l'ajout d'un paramètre String permettant de préciser un jeu de caractère. La fonctionnalité est prévue par OutputStreamWriter.
/** * Creates a new PrintWriter, without automatic line flushing, with the * specified file. This convenience constructor creates the necessary * intermediate {@link java.io.OutputStreamWriter OutputStreamWriter}, * which will encode characters using the {@linkplain * java.nio.charset.Charset#defaultCharset() default charset} for this * instance of the Java virtual machine. * * @param file * The file to use as the destination of this writer. If the file * exists then it will be truncated to zero size; otherwise, a new * file will be created. The output will be written to the file * and is buffered. * * @throws FileNotFoundException * If the given file object does not denote an existing, writable * regular file and a new regular file of that name cannot be * created, or if some other error occurs while opening or * creating the file * * @throws SecurityException * If a security manager is present and {@link * SecurityManager#checkWrite checkWrite(file.getPath())} * denies write access to the file * * @since 1.5 */ public PrintWriter(File file) throws FileNotFoundException { this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))), false); }
Ici le constructeur prend un File. On peut construire un FileOutputStream depuis un objet File et pas son nom de fichier.
/** * Creates a new PrintWriter, without automatic line flushing, with the * specified file and charset. This convenience constructor creates the * necessary intermediate {@link java.io.OutputStreamWriter * OutputStreamWriter}, which will encode characters using the provided * charset. * * @param file * The file to use as the destination of this writer. If the file * exists then it will be truncated to zero size; otherwise, a new * file will be created. The output will be written to the file * and is buffered. * * @param csn * The name of a supported {@linkplain java.nio.charset.Charset * charset} * * @throws FileNotFoundException * If the given file object does not denote an existing, writable * regular file and a new regular file of that name cannot be * created, or if some other error occurs while opening or * creating the file * * @throws SecurityException * If a security manager is present and {@link * SecurityManager#checkWrite checkWrite(file.getPath())} * denies write access to the file * * @throws UnsupportedEncodingException * If the named charset is not supported * * @since 1.5 */ public PrintWriter(File file, String csn) throws FileNotFoundException, UnsupportedEncodingException { this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), csn)), false); }
Pas de commentaire, comme l'autre constructeur avec le charset: on utilise OutputStreamWriter, qui intègre cette possibilité.
RETOUR HAUT