Java Reference
In-Depth Information
out.printf("%d attrs%n", attrs.length);
for (int i = 0; i < attrs.length; i++) {
Attr attr = attrs[i];
out.printf("%s=%s%n",
attr.getName(), attr.getValue());
}
out.flush();
}
public static Attr[] scanAttrs(Reader source) {
Scanner in = new Scanner(source);
int count = in.nextInt();
in.nextLine(); // skip rest of line
Attr[] attrs = new Attr[count];
Pattern attrPat =
Pattern.compile("(.*?)=(.*)$", Pattern.MULTILINE);
for (int i = 0; i < count; i++) {
in.findInLine(attrPat);
MatchResult m = in.match();
attrs[i] = new Attr(m.group(1), m.group(2));
}
return attrs;
}
The printAttrs method uses printf to print an attribute in one line, using
a = character to separate name from value. The scanAttrs method will
read such a file back in. It uses a combination of stream-based and line-
based Scanner calls. It first reads back the count as an int and then con-
sumes the rest of the line (the "attrs" from the printf is just for human
readability). It then loops getting name/value lines. The pattern used
has two capture groups, the first to get the attribute name (using a non-
greedy qualifier to get the fewest possible characters before the = ) and
the second to get the value. These groups are pulled out to create the
actual Attr object.
 
Search WWH ::




Custom Search