Java
  Home arrow Java arrow Page 2 - Java Print Streams
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Dedicated Servers  
Actuate Whitepapers 
VeriSign Whitepapers 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
JAVA

Java Print Streams
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 2
    2007-06-14

    Table of Contents:
  • Java Print Streams
  • Print Versus Write
  • Line Breaks
  • Error Handling
  • Formatter

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
    Iron Speed
     
    ADVERTISEMENT

    Free Web 2.0 Code Generator! Generate data entry and reporting .NET Web apps in minutes. Quickly create visually stunning, feature-rich apps that are easy to customize and ready to deploy. Download Now!

    Java Print Streams - Print Versus Write


    (Page 2 of 5 )

    The reason you might choose a PrintStream instead of a raw OutputStream is for its print()andprintln()methods. These methods each convert their argument to aStringand then convert theStringto bytes in a specific encoding before writing it to the underlying output stream. For example, consider thisPrintStreamconnected to a file named numbers.dat:

      PrintStream out = new PrintStream(new FileOutputStream("numbers.dat"));

    Suppose we use a simple for loop to write the numbers from 0 to 127 in that file:

      for (int i = 0; i <= 127; i++) out.write(i);

    When we’re done, the file contains 128 bytes: the first byte is 0, the second is 1, the third is 2, and so on. It’s pure binary data. If you try to open it up in a text editor you’ll see goop, as shown in Figure 7-1. Some of those binary numbers happen to be interpretable as ASCII text, but that’s an accident. They’re really just bytes. Many of them aren’t printable.


    Figure 7-1.  A binary file in a text editor

    Now suppose instead of using thewrite()method we use theprint()method:

      for (int i = 0; i <= 127; i++) out.print(i);

    This time thePrintStreamdoes not write raw binary data in the file. Instead, it converts each number into its ASCII string equivalent and writes that string. For instance, instead of writing the byte 20, it writes the character 2 followed by the character 0. If you open the file in a text editor now, you’ll see something like the screenshot shown in Figure 7-2.


    Figure 7-2.  A text file in a text editor

    It’s not absolutely guaranteed that the string will be written in ASCII. On a few IBM mainframes, EBCDIC might be used instead. However, given the range of characters used here, it’s pretty likely that the resulting file will make sense when interpreted as ASCII. More on this point shortly.

    Theprintln()method prints a platform-specific line terminator after printing its argument. Suppose instead of using theprint()method we use theprintln()method:

      for (int i = 0; i <= 127; i++) out.println(i);

    Then the output is even neater, as shown in Figure 7-3.

    These examples used ints, but thePrintStream class hasprint()andprintln( )methods for every Java data type. The method signatures are:

      public void print(boolean b)
      public void print(char c)
      public void print(int i)
      public void print(long l)
      public void print(float f)
      public void print(double d)
      public void print(char[] s)
      public void print(String s)
      public void print(Object o)
      public void println(boolean b)
      public void println(char c)
      public void println(int i)
      public void println(long l)
      public void println(float f)
      public void println(double d)
      public void println(char[] s)
      public void println(String s)
      public void println(Object o)

    You can pass anything at all to aprint()method. Whatever argument you supply is guaranteed to match at least one of these methods. Object types are converted to


    Figure 7-3.  A text file with line breaks

    strings by invoking theirtoString()methods. Primitive types are converted with the appropriateString.valueOf()methods.

    One aspect of makingSystem.outsimple for quick jobs is not in thePrintStream class at all, but in the compiler. Because Java overloads the+operator to signify concatenation of strings, primitive data types, and objects, you can pass multiple variables to theprint()andprintln()methods, which are then converted to strings and concatenated. For example, consider the line:

      System.out.println("As of " + (new Date()) + " there have been over "
      
    + hits + " hits on the web site." );

    The compiler rewrites this complicated expression as:

      StringBuffer sb = new StringBuffer();
      sb.append("As of ");
      Date d = new Date();
      sb.append(d);
      sb.append(" there have been over ");
      sb.append(hits);
      sb.append(" hits on the web site.")
      String s = sb.toString();
      System.out.println(s);

    TheStringBuffer append()method is overloaded in much the same way that theprint()andprintln()methods are; as a result, it can handle any Java data type.

    More Java Articles
    More By O'Reilly Media


       · This article is an excerpt from the book "Java I/O, Second Edition," published by...
     

    Buy this book now. This article is excerpted from chapter seven of Java I/O, Second Edition, written by Elliotte Rusty Harold (O'Reilly, 2006; ISBN: 0596527500). Check it out today at your favorite bookstore. Buy this book now.

    JAVA ARTICLES

    - Deploying Multiple Java Applets as One
    - Deploying Java Applets
    - Understanding Deployment Frameworks
    - Database Programming in Java Using JDBC
    - Extension Interfaces and SAX
    - Entities, Handlers and SAX
    - Advanced SAX
    - Conversions and Java Print Streams
    - Formatters and Java Print Streams
    - Java Print Streams
    - Wildcards, Arrays, and Generics in Java
    - Wildcards and Generic Methods in Java
    - Finishing the Project: Java Web Development ...
    - Generics and Limitations in Java
    - Getting Started with Java Web Development in...

    Iron Speed

    Iron Speed





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 4 hosted by Hostway