Java Reference
In-Depth Information
2$ denotes the argument index (2). Use this if the variables to be formatted do not follow the
same order as provided in the format string or if you want to output the same variable more
than once.
+0 for flags. This is a series of characters including + to specify that a number should be for-
matted with a sign, 0 to specify that 0 is the padding character (if not provided, a space is
used instead), - to specify that padding should be added on the right (the number will be left
aligned), and , to specify that a locale-specific thousands separator should be used.
20 is the minimum width of the formatted value. The value will be padded if necessary to
obtain this width.
.10 is the precision (10). For decimals, this is the mathematical precision of the formatted
value. For % s and other conversions, this is the maximum width of the formatted value, trun-
cated if necessary.
f is the actual conversion.
Returning to the file copy program we introduced before, recall that we're copying the file in a raw,
byte-by-byte manner. While this is fine, byte streams actually represent low-level input/output. Since
the grocery list is a text file containing character data, it might be better to use a higher-level stream
type geared more toward this purpose, namely character streams.
character streams
Character streams translate Unicode characters (used internally within Java) to and from the charac-
ter locale specified. This stream is equal to a byte stream but adapts to the local character set and is
thus ready for internationalization.
All character streams subclass Reader and Writer , e.g., FileReader and FileWriter . These classes
are not subclasses of the byte stream InputStream and OutputStream classes, but offer a similar set
of methods, e.g., read and write . The next Try It Out reworks the file copier example to use char-
acter streams instead of byte streams.
Copying Files with Character Streams
try it out
In this Try It Out, you will copy a grocery list using character streams.
1.
We will modify the FileCopier class we created earlier. Refer to the earlier Try It Out if you have
not done so already. Make sure the groceries.txt file is still present.
2.
Edit the FileCopier class to look as follows:
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileCopier {
public static void main(String[] args) {
try (
Reader in = new FileReader("groceries.txt");
 
Search WWH ::




Custom Search