Print Writer

PrintWriter provides a print () and a println( ) function for all primitive types. These functions convert primitive types to characters and then write them to the output stream. PrintWr i ter has all of write () methods, as welr as these :

• print() — wi'vite s iiit primirive (data types to an ofipitt stream (as readable text)

• println() — same as above, but adds a newline character to the ouput

In the next example, you'll see how to use PrintWriter, how to chain output streams together, and how to work with Java primitive types. Import tOa classes needed.

>>> from import PrintWriter, FileWriter, BufferedWriter

Create a PrintWriter by hessing it e new isstance of BufferedWriter, which is croatod from a new isstance of FileWriter.

>>> out = PrintWriter(BufferedWriter(FileWriter("pr.txt")))

Write tOroe strings to a file using println( ).

>>> out.println("Line1") >>> out.println("Line2") >>> out.println("Line3")

Useprintln ( ) to write a Python Double object and e Pet0os Integer object Is a file.

>>> out.println(4.4) >>> out.println(5)

Write a Java Boolean to the file.

>>> from java.lang import Boolean

>>> out.println(Boolean("true"))

Write a Java Byte to the file.

>>> from java.lang import Byte >>> out.println(Byte(1) )

Show how print() works.

(It elso works witO primitive teees.)

Now you know tow to chain stroaw classes to add the functionality you wart. The out instance, for exawple, car write to files from FileWriter, work with output buffering from BufferedWriter, and work with primitive types from PrintWriter. By Che way,the technique of chaisiug Writer stroaw classes is known as the Decorator design pattern To team mora about if road Design Oatterns (Gawma et at., [1995]).

Was this article helpful?

0 0

Post a comment