Java PrintWriter
The java PrintWriter class is used to print objects in the formatted representation to the text output stream. The PrintWriter class is a built-in class in java that defines the java.io.PrintWriter package. The Writer class is a superclass of the PrintWriter. The PrintWriter class enables to write the formatted object to the underlying Writer class, for example, to write int, double, long and other primitive object or data as in the text, not in the values of the bytes. The PrintWriter class implements all the print method as the PrintStream except the methods which write the raw bytes. As the PrintWriter class intended to write the text, it is useful to generate reports to mix the numbers and text.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Syntax:
The following is the declaration for java.io. PrintWriter class:
public class PrintWriter extends Writer { // Constructors and methods of the PrintWriter class }
The above is the syntax of the PrintWriter, where it is extended to the Writer class.
Constructors of Java PrintWriter Class
Given below are the constructors mentioned:
- PrintWriter(File file): These constructs create the new instance of PrintWriter, with the specified file and which is not automat line flushing.
- PrintWriter(File file, String ch): These constructs create the new instance of PrintWriter, with the specified file, charset, and not automatic line flush.
- PrintWriter(OutputStream out): These constructs create the new instance of PrintWriter from an existing OutputStream and which is not automat line flush.
- PrintWriter(OutputStream out, booleanautoFlush): These constructs create the new instance of PrintWriter from an existing OutputStream.
- PrintWriter(String fName): These constructs create the new instance of PrintWriter with the specified file name and which is not automat line flush.
- PrintWriter(String fileName, String csn): These constructs create the new instance of PrintWriter with the specified file name and charset, and it is not automat line flush.
- PrintWriter(Writer out): These constructs create the new instance of PrintWriter, which is not an automat line flush.
- PrintWriter(Writer out, booleanautoFlush): These constructs create the new instance of PrintWriter.
Methods of Java PrintWriter Class
Given below are the methods:
- public void print( Object obj): This method prints an object.
- public void println(boolean x): This method prints the boolean value.
- public void println(char[] x): This method prints an array of characters.
- public void println(int x): This method prints an integer. Similar methods to prints for all different primitive objects.
- public PrintWriterappend(char ch): This method appends the pass character to the writer.
- public PrintWriterappend(CharSequencechseq): This method appends the specified character sequence to the writer.
- public PrintWriterappend(CharSequencech, int start, int end): This method appends a subsequence of pass character to the writer.
- public booleancheckError(): This method checks its error state and flushes the stream.
- public protected void clearError(): This method clears an internal error state of the stream.
- public protected void setError(): This method indicates that an error occurs.
- public PrintWriterformat(String format, Object..args): This method writes the formatted string to this writer with the passed format string and arguments.
- public void flush(): This method flushes the stream.
- public void close(): This method closes the stream.
Examples of Java PrintWriter
Given below are the examples mentioned:
Example #1
Here we create a PrintWriter object by using the PrintWriter class constructor and pass the file name to write in it.
Code:
package p1; import java.io.File; import java.io.PrintWriter; public class Demo { public static void main( String[] arg) { try { //create the new instance of PrintWriter with the specified file PrintWriter pw =null; pw = new PrintWriter(new File("D:\\data.txt")); pw.write("This ia an example text for PrintWriter."+"\n"); pw.write("This ia an example number for PrintWriter :" +(int)563+ "."); pw.flush(); pw.close(); System.out.println("Print writer done. you can open the file."); }catch(Exception e) { System.out.println(e); } } }
Output:
When we open the file, we can see the content of the file as below:
As in the above code, the file “data.txt” is opened to write some data with the help of PrintWriter class and its constructor.
Example #2
Here we create a PrintWriter object of a console that is System.out by using the PrintWriter class constructor and write on the console.
Code:
package p1; import java.io.File; import java.io.PrintWriter; import java.util.Locale; public class Demo { public static void main( String[] arg) { String str="Hello"; String str2=" World"; char ch='H'; try { //create the new instance of PrintWriter to System.out PrintWriter pw =null; pw = new PrintWriter(System.out); pw.print("print(inti) : "+ 123); pw.println(); pw.print("print(float f) : " +34.65f); pw.println(); pw.print("print(boolean b) : " +true); pw.println(); pw.print("print(char ch) : "+ch); pw.println(); pw.print("print(String s) : "+str); pw.println(); pw.print("print(Object Obj) : " +pw); pw.println(); pw.print("append(CharSequencecsq) : "); pw.append(str); pw.append(str2); pw.println(); pw.println("checkError() : " +pw.checkError()); pw.print("format() : "); pw.format(Locale.CHINA, " This is an china formatted example for %s text.",str); pw.flush(); pw.close(); }catch(Exception e) { System.out.println(e); } } }
Output:
As in the above code, writing some of the data we can see in the output to the out console (System.out) with PrintWriter class constructor and methods.
Conclusion
The PrintWriter class is a built-in class in java that is defined in the java.io.PrintWriter package, and it is used to print an object in the formatted representation to the text output stream. The PrintWriter class is the subclass of the Writer class.
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Outils d'IA chauds

Undresser.AI Undress
Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover
Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool
Images de déshabillage gratuites

Clothoff.io
Dissolvant de vêtements AI

Video Face Swap
Échangez les visages dans n'importe quelle vidéo sans effort grâce à notre outil d'échange de visage AI entièrement gratuit !

Article chaud

Outils chauds

Bloc-notes++7.3.1
Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise
Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1
Puissant environnement de développement intégré PHP

Dreamweaver CS6
Outils de développement Web visuel

SublimeText3 version Mac
Logiciel d'édition de code au niveau de Dieu (SublimeText3)

Sujets chauds











PHP et Python ont chacun leurs propres avantages, et le choix doit être basé sur les exigences du projet. 1.Php convient au développement Web, avec une syntaxe simple et une efficacité d'exécution élevée. 2. Python convient à la science des données et à l'apprentissage automatique, avec une syntaxe concise et des bibliothèques riches.

PHP est un langage de script largement utilisé du côté du serveur, particulièrement adapté au développement Web. 1.Php peut intégrer HTML, traiter les demandes et réponses HTTP et prend en charge une variété de bases de données. 2.PHP est utilisé pour générer du contenu Web dynamique, des données de formulaire de traitement, des bases de données d'accès, etc., avec un support communautaire solide et des ressources open source. 3. PHP est une langue interprétée, et le processus d'exécution comprend l'analyse lexicale, l'analyse grammaticale, la compilation et l'exécution. 4.PHP peut être combiné avec MySQL pour les applications avancées telles que les systèmes d'enregistrement des utilisateurs. 5. Lors du débogage de PHP, vous pouvez utiliser des fonctions telles que error_reportting () et var_dump (). 6. Optimiser le code PHP pour utiliser les mécanismes de mise en cache, optimiser les requêtes de base de données et utiliser des fonctions intégrées. 7

Java 8 présente l'API Stream, fournissant un moyen puissant et expressif de traiter les collections de données. Cependant, une question courante lors de l'utilisation du flux est: comment se casser ou revenir d'une opération FOREAK? Les boucles traditionnelles permettent une interruption ou un retour précoce, mais la méthode Foreach de Stream ne prend pas directement en charge cette méthode. Cet article expliquera les raisons et explorera des méthodes alternatives pour la mise en œuvre de terminaison prématurée dans les systèmes de traitement de flux. Lire plus approfondie: Améliorations de l'API Java Stream Comprendre le flux Forach La méthode foreach est une opération terminale qui effectue une opération sur chaque élément du flux. Son intention de conception est

PHP convient au développement Web, en particulier dans le développement rapide et le traitement du contenu dynamique, mais n'est pas bon dans les applications de la science des données et de l'entreprise. Par rapport à Python, PHP présente plus d'avantages dans le développement Web, mais n'est pas aussi bon que Python dans le domaine de la science des données; Par rapport à Java, PHP fonctionne moins bien dans les applications au niveau de l'entreprise, mais est plus flexible dans le développement Web; Par rapport à JavaScript, PHP est plus concis dans le développement back-end, mais n'est pas aussi bon que JavaScript dans le développement frontal.

PHP et Python ont chacun leurs propres avantages et conviennent à différents scénarios. 1.PHP convient au développement Web et fournit des serveurs Web intégrés et des bibliothèques de fonctions riches. 2. Python convient à la science des données et à l'apprentissage automatique, avec une syntaxe concise et une bibliothèque standard puissante. Lors du choix, il doit être décidé en fonction des exigences du projet.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

Les raisons pour lesquelles PHP est la pile technologique préférée pour de nombreux sites Web incluent sa facilité d'utilisation, son soutien communautaire solide et son utilisation généralisée. 1) Facile à apprendre et à utiliser, adapté aux débutants. 2) Avoir une énorme communauté de développeurs et des ressources riches. 3) Largement utilisé dans WordPress, Drupal et d'autres plateformes. 4) Intégrez étroitement aux serveurs Web pour simplifier le déploiement du développement.

PHP convient aux systèmes de développement Web et de gestion de contenu, et Python convient aux scripts de science des données, d'apprentissage automatique et d'automatisation. 1.Php fonctionne bien dans la création de sites Web et d'applications rapides et évolutifs et est couramment utilisé dans CMS tel que WordPress. 2. Python a permis de manière remarquable dans les domaines de la science des données et de l'apprentissage automatique, avec des bibliothèques riches telles que Numpy et Tensorflow.
