Java
  Home arrow Java arrow Page 4 - 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 
Moblin 
JMSL Numerical Library 
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: 4 stars4 stars4 stars4 stars4 stars / 3
    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
     
     
    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 - Error Handling


    (Page 4 of 5 )

    You may have noticed something a little funny with the code fragments in this chapter: I haven’t put any try-catch blocks around them. That’s not an oversight. PrintStream methods never throw IOExceptions. Each method in the class catchesIOException. When an exception occurs, an internal flag is set totrue. You can test this flag using thecheckError()method:

      public boolean checkError()

    This method returnstrueif this print stream has ever encountered an error during its lifetime. Most of the time, you just ignore this, since print streams are only used in situations where exhaustive error checking is unnecessary.

    There’s also a protectedsetError()method you can use to signal an error from a subclass:

      protected void setError()

    Once an error has been set, there’s no way to unset it. Generally, once aPrintStreamhas encountered an error, all further writes to it silently fail. It’s not the failure but the silence that makesPrintStream unsuitable for most applications.

    printf()

    I was inspired to write the first edition of this book by the numerous questions I received about why there was no printf() function in Java. Part of the goal of that edition was to explain to readers why they didn’t actually need it. Thus, I was a little perturbed when Java 5 added printf(). Personally, I still don’t think Java needs printf(), but it’s here now, so let’s talk about it.

    Theprintf()method makes heavy use of Java 5’s new varargs feature. That is, a single method definition can support any number of arguments. In this case, the signature is:

      public PrintStream printf(String format, Object... args)

    A typical invocation looks like this:

      System.out.printf("There are %f centimeters in %f inches.", 2.54*inches, inches);

    If you’re an old C hack, this is like coming home. The first argument is a format string containing both literal text and tags beginning with percent signs (%). To form the output, each tag is replaced by the corresponding argument that follows the format string. If the format string is the zeroth argument, the first tag is replaced by the first argument, the second tag by the second argument, and so forth. If there are more tags than arguments,printf()throws ajava.util.MissingFormatArgumentException. This is a subclass ofIllegalFormatException, which is a runtime exception, so you don’t have to catch it. If there are more arguments than tags, the extra arguments are silently ignored.

    Printf()

    The letter(s) after the percent sign in the format tag specify how the number is interpreted. For instance,%fmeans that the number is formatted as a floating-point number with a decimal sign.%dformats the argument as a decimal integer.%xformats the number as a hexadecimal integer.%Xalso formats the number as a hexadecimal integer but uses the uppercase letters A–F instead of the lowercase letters a–f to represent 10–15.

    Most of the time, changing a lowercase conversion specifier to uppercase changes the formatted string from lowercase to uppercase. However, there are a few exceptions to this rule.

    There are a couple of dozen tags for different kinds of data. Not all data is compatible. For instance, if you use%xto format adouble as a hexadecimal integer,printf()throws ajava.util.IllegalFormatConversionException. Again, this is a runtime exception and a subclass ofIllegalFormatException.

    So far, this isn’t anything that can’t be done easily withprintln()and string concatenation. What makesprintf()more convenient for some uses is that the tags can also contain width and precision specifiers. For example, suppose we wrote the previous statement like this instead:

      System.out.printf("There are %.3f centimeters in %.2f feet.", 2.54*feet, feet);

    %.3fmeans that the centimeters will be formatted as a decimal number with exactly three digits after the decimal point.%.2fmeans that the number will be rounded to only two decimal places. This gives more legible output, like “There are 21.691 centimeters in 8.54 feet” instead of “There are 21.690925 centimeters in 8.539734 feet.”

    A number before the decimal point in the format tag specifies the minimum width of the formatted string. For instance,%7.3fformats a decimal number exactly seven characters wide with exactly three digits after the decimal point. Those seven characters include the decimal point, so there will be exactly three digits to the left of the decimal point. If the number is smaller than 100, it will be padded on the left with spaces to make seven characters. Zeros will be added to the right of the decimal point if necessary to pad it to three decimal places.

    Consider this Java 1.4 code fragment that prints a three-column table of the angles between 0 and 360 degrees in degrees, radians, and grads, using onlyprintln():

      for (double degrees = 0.0; degrees < 360.0; degrees++) {
       
    double radians = Math.PI * degrees / 180.0;
       
    double grads = 400 * degrees / 360;
       
    System.out.println(degrees + " " + radians + " " + grads);
      }

    Its output looks like this (not very pretty):

      0.0 0.0 0.0
      1.0 0.017453292519943295 1.1111111111111112
     
    2.0 0.03490658503988659 2.2222222222222223
      3.0 0.05235987755982988 3.3333333333333335
      ...

    In Java 5,printf()can easily format each number exactly five characters wide with one digit after the decimal point:

      for (double degrees = 0.0; degrees < 360.0; degrees++) {
       
    double radians = Math.PI * degrees / 180.0;
       
    double grads = 400 * degrees / 360;
       
    System.out.printf("%5.1f %5.1f %5.1f\n", degrees , radians, grads);
     
    }

    Here’s the start of the output:

      0.0   0.0   0.0
      1.0   0.0   1.1
      2.0   0.0   2.2
      3.0   0.1   3.3
      ...

    Notice how nicely everything lines up in a monospaced font? This is incredibly useful for the two dozen programmers using Java to generate reports for VT-100 terminals and letter-quality printouts on green-and-white barred computer paper. (Those readers who haven’t written any software like that since 1984, and certainly those readers who weren’t even born in 1984, should now see why I’m less than thrilled with the addition of this 1970s technology to a 21st-century language.)

    Of course, programmers printing text in proportional-width fonts, GUI table components, HTML reports, XML documents styled with XSL stylesheets, and any other output format produced since 1992 may be less enamored of this style of programming. Anyway, Java has it now. You don’t have to use it (or read the rest of this chapter) if you don’t need it.

    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...







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