braju.com
Java printf & scanf (beta)

com.braju.beta.format
Class FormatWriter

java.lang.Object
  |
  +--java.io.Writer
        |
        +--java.io.BufferedWriter
              |
              +--com.braju.beta.format.FormatWriter

public class FormatWriter
extends java.io.BufferedWriter

Provides formatted output a'la true C-style printf() with any number of parameters.


Format specification

This is the format of one conversion specification:

    __%__ _________ __ _________ __ __________________ __type__
         |         |  |         |  |                  |
         |__flags__|  |__width__|  |__./:__precision__|
or
% flag* [width] [{.|:}precision] type

Field description

flags Justification of output and printing of signs, blanks, decimal points, octal, and hexadecimal prefixes.

width Minimum number of characters (bytes) output.

precision Maximum number of characters (bytes) printed for all or part of the output field, or minimum number of digits printed for integer values. For floating-point values/outputs, the precision will, if prefixed by '.' (period) control the number of digits outputted after the period. If instead the precision is prefixed by ':' (colon) the precision value will control the number of significant digit outputted [extension to ANSI-C]. For more information see examples below.


Flag Brief description
^ Central adjusted, otherwise right adjusted. [not an ANSI-C standard].
- (minus sign) Left adjusted, otherwise right adjusted.
+ (plus sign) Prefix the output value with a sign (+ or -) if the output value is of a signed type. Default is that sign appears only for negative values (-).
' ' (blank) A nonnegative value will have a space prepended. The + flag overrides the blank flag if both appear, and a positive value will be output with a sign.
# (pound) Alternative form. When used with the o, x, X, b or B formats, the # flag prefixes any output value with 0, 0x, 0X, 0b or 0B, respectively. With the p and P formats the output value will be prefixed with 0x and 0X respectively. When used with the f, e, or E formats, the # flag forces the output value to contain a decimal point in all cases. When used with the c format, the # flag forces the output value to be in UTF-encoding, e.g. \u0041.
0 (zero) When used with the b, B, d, i, o, x, X, e, E, f, g, or G formats, the 0 flag causes leading 0's to pad the output to the field width. The 0 flag is ignored if the - flag is specified.

Width Brief description
* (asterix) The value for the width will be obtained from the parameter list. If the value is negative the output will be left-justified.
n (an integer) A nonnegative integer for the width; e.g. 8.

Precision Brief description
* (asterix) The value for the precision will be obtained from the parameter list.
n (an integer) A nonnegative integer for the precision; e.g. 3.

Conversion
type
Corresponding argument
will be printed as
b a binary integer. [extension to ANSI-C].
c a character.
d, i a decimal integer.
e,E a scientific floating point number; e.g. 1.23E-03.
f a floating point number; e.g. 0.00123.
g,G %e or %E is used if the exponent is less than -4 or greater than or equal to the precision; otherwise %f is used. Trailing zeros are truncated, and the decimal point appears only if one or more digits follow it. Precision specifies the maximum number of significant digits printed.
l,L a logical value, i.e. a boolean; e.g. true, FALSE. Also support for C-style booleans, i.e. 0 or 1 (<>0). [extension to ANSI-C].
o an octal integer.
p,P hashValue of an object outputted as a hexadecimal integer. [extension to ANSI-C].
s a string. All characters in String is printed or as many as precision specifies.
x,X a hexadecimal integer.
% There is no corresponding argument, i.e. To output "%" one have to put "%%" in the format string.

Example:

   FormatWriter out = new FormatWriter(new FileWriter("foo.bar"));
   out.write("Please, try to support %3.2f%% %s!\n",
                 new Parameters(100).add("Java"));
writes following to file foo.bar
Please, try to support 100.00% Java!
You can also do like this
   Parameters p = new Parameters();
   Writer out0 = new OutputStreamWriter(System.out);
   FormatWriter out = new FormatWriter(out0);
   out.write("Please, try to support %.2f%% %s or, "+
     "at least to %:3f%%.\n", p.add(100).add("Java").add(99.9453));
   out.write("I heard of companies only supporting it to %:5f.",
     p.add(1e-3));
which gives
Please, try to support 100.00% Java or, at least to 99.9%.
I heard of companies only supporting it to 0.0010%.

Note that the above examples can be simplified by using the printf & scanf methods defined in com.braju.format.Format.

Note that if your program are supposed to run under Java1.0.2 you should use com.braju.format.FormatOutputStream instead. It works the same.

See Also:
Format, Format102, FormatOutputStream, Parameters

Constructor Summary
FormatWriter(java.io.Writer out)
          Create a new character-stream writer whose destination is the given stream.
 
Method Summary
 void addConversionParser(com.braju.beta.format.ConversionParser parser)
          Add a new parser for the format string, e.g.
 void close()
          Close the stream, flushing it first [...].
 FormatString compileFormatString(java.lang.String fmt)
          Compile a format string and return the result as a FormatString [...].
static FormatWriter conform(java.io.Writer out)
          Static method that always returns an instance of this class regardless of the input is an instance of this class or not [...].
 void flush()
          Flush the stream [...].
 com.braju.beta.format.ConversionParser[] getConversionParsers()
          Gets the conversion parsers.
 boolean getModifyLineSeparators()
          Checks wether the automatic replacement of newlines is turned on or off.
 void removeConversionParser(com.braju.beta.format.ConversionParser parser)
          Remove a previously added format string parser [...].
 void resetFormatStringCompiler()
          Resets the internal FormatStringCompiler to the default printf-format string compiler.
 void setModifyLineSeparators(boolean activated)
          Turns on or off the automatic replacement of all occurenses of newlines ('\r', '\n' and '\r\n') found on the input stream [...].
 void write(char[] cbuf, int off, int len)
          Write a portion of an array of characters [...].
 int write(FormatString fmtstr, Parameters parameters)
          Write characters in a C-sprintf manner according to the specified FormatString and its related parameters.
 void write(int ch)
          Write a single character [...].
 void write(java.lang.String str)
          Write characters in a C-sprintf manner according to the specified format [...].
 int write(java.lang.String fmt, Parameters parameters)
          Write characters in a C-sprintf manner according to the specified format and its related parameters.
 
Methods inherited from class java.io.BufferedWriter
newLine, write
 
Methods inherited from class java.io.Writer
write
 
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

FormatWriter

public FormatWriter(java.io.Writer out)
Create a new character-stream writer whose destination is the given stream.
Method Detail

setModifyLineSeparators

public void setModifyLineSeparators(boolean activated)
Turns on or off the automatic replacement of all occurenses of newlines ('\r', '\n' and '\r\n') found on the input stream [...]. If a newline is found it is changed with a '\n' if the automatic replacement is turn on. This property is by default activated.

getModifyLineSeparators

public boolean getModifyLineSeparators()
Checks wether the automatic replacement of newlines is turned on or off.

conform

public static FormatWriter conform(java.io.Writer out)
Static method that always returns an instance of this class regardless of the input is an instance of this class or not [...]. If the given stream already is a FormatWriter the same instance is returned, otherwise a new instance of FormatWriter is created.
Parameters:
out - Stream to be conformed into a format writer
Returns:
a FormatWriter with the given stream as a destination

addConversionParser

public void addConversionParser(com.braju.beta.format.ConversionParser parser)
Add a new parser for the format string, e.g. a QutationParser [...]. The new parser is insert first in the queue; the queue is a LIFO-queue. This means that you can always override previously added parsers with a new one. For more information, see FormatStringCompiler.
Parameters:
parser - Conversion parser to be added

removeConversionParser

public void removeConversionParser(com.braju.beta.format.ConversionParser parser)
Remove a previously added format string parser [...]. If the parser were never added nothing happens.
Parameters:
parser - Conversion parser to be removed

resetFormatStringCompiler

public void resetFormatStringCompiler()
Resets the internal FormatStringCompiler to the default printf-format string compiler.

getConversionParsers

public com.braju.beta.format.ConversionParser[] getConversionParsers()
Gets the conversion parsers.
Returns:
an array of all registered conversion parsers

compileFormatString

public FormatString compileFormatString(java.lang.String fmt)
Compile a format string and return the result as a FormatString [...]. It is recommended to use this method if the same format string will be used several times.
When the format string is parsed, all conversion parsers, starting with the first, is asked if they are "interrested" (trigged by) the current character. If one conversion parser's answer is yes, then that parser start parsing the string. If the parsing succeed a FormatString is returned, otherwise next "interrested" parser gets its turn. If now conversion parser succeed to parser from the current character, no characters are read, and then null is returned. No exception is thrown.
Parameters:
fmt - String containing conversion flags to be compiled
Returns:
a FormatString representing a precompiled format string.

write

public int write(FormatString fmtstr,
                 Parameters parameters)
          throws ParseException,
                 java.io.IOException
Write characters in a C-sprintf manner according to the specified FormatString and its related parameters.
Parameters:
fmtstr - Format string specifying the output
parameters - Parameters containing values to replace the format flags
Returns:
the number of characters written
Throws:
java.io.IOException - If an I/O error occurs

write

public int write(java.lang.String fmt,
                 Parameters parameters)
          throws ParseException,
                 java.io.IOException
Write characters in a C-sprintf manner according to the specified format and its related parameters.
Parameters:
fmt - Format string specifying the output
parameters - Parameters containing values to replace the format flags
Returns:
the number of characters written
Throws:
java.io.IOException - If an I/O error occurs

write

public void write(java.lang.String str)
           throws ParseException,
                  java.io.IOException
Write characters in a C-sprintf manner according to the specified format [...]. No parameters are used. Note that it is not exactly the same as the inherited write(String), since the format "%%" will be printed as a single "%".
Overrides:
write in class java.io.Writer
Parameters:
str - String to be written
Throws:
java.io.IOException - If an I/O error occurs

write

public void write(int ch)
           throws java.io.IOException
Write a single character [...]. The character to be written is contained in the 16 low-order bits of the given integer value; the 16 high-order bits are ignored. No formatting is performed.
Overrides:
write in class java.io.BufferedWriter
Throws:
java.io.IOException - If an I/O error occurs

write

public void write(char[] cbuf,
                  int off,
                  int len)
           throws java.io.IOException
Write a portion of an array of characters [...]. No formatting is performed, i.e. this method writes the character buffer to the destionation as is.
Overrides:
write in class java.io.BufferedWriter
Parameters:
cbuf - Array of characters
off - Offset from which to start writing characters
len - Number of characters to write
Throws:
java.io.IOException - If an I/O error occurs

flush

public void flush()
           throws java.io.IOException
Flush the stream [...]. If the stream has saved any characters from the various write() methods in a buffer, write them immediately to their intended destination. Then, if that destination is another character or byte stream, flush it. Thus one flush() invocation will flush all the buffers in a chain of Writers and OutputStreams.
Overrides:
flush in class java.io.BufferedWriter
Throws:
java.io.IOException - If an I/O error occurs

close

public void close()
           throws java.io.IOException
Close the stream, flushing it first [...]. Once a stream has been closed, further write() or flush() invocations will cause an IOException to be thrown. Closing a previously-closed stream, however, has no effect.
Overrides:
close in class java.io.BufferedWriter
Throws:
java.io.IOException - If an I/O error occurs

braju.com
Java printf & scanf (beta)

Copyright 1997-2000, Henrik Bengtsson.