Java 1.5 Tiger A Developers Notebook [Electronic resources]

David Flanagan, Brett McLaughlin

نسخه متنی -صفحه : 131/ 89
نمايش فراداده

9.1 Creating a Formatter

The simplest way to get started with the Formatter class is to create a new instance of it, and then do some work. You'll see in later labs that this isn't always the best way to go about business, but it's as good a starting point as any.

9.1.1 How do I do that?

Formatter has several constructors, listed here:

// No-args version -- not particularly useful
public Formatter( );
// Basically, the no-args version with a locale
public Formatter(Locale l);
// Creates a formatter with the supplied destination (sink)
public Formatter(Appendable a);
// Creates a formatter with the destination, using the supplied locale
public Formatter(Appendable a, Locale l);
// Creates a new formatter with the filename as the sink
public Formatter(String fileName);
// Creates a new formatter with a file as the sink, using the specified
charset
public Formatter(String fileName, String csn);
// Same as above, but with a locale
public Formatter(String fileName, String csn, Locale l);	

This is a pretty wide range of options, and should cover your most basic formatting needs. Thus, you could use code such as this to create a Formatter targeted at a StringBuilder:

StringBuilder sb = new StringBuilder( );
Formatter formatter = new Formatter(sb, Locale.FRANCE);
// The next lab details what you can do with Formatter

I realize this seems sort of trivial, but it's meant to be. Formatter is a new class, but not a particularly difficult one to master.

NOTE

If you're unfamiliar with StringBuilder, check out the lab at the end of this chapter.