Java Reference
In-Depth Information
Attempts to find the given pattern before the next line separ-
ator is encountered. The delimiters of the scanner are ignored
during this search. If the pattern is found then the scanner
advances to the next position after the matching input, and
the matching input is returned. If the pattern is not found
then null is returned and the position of the scanner is un-
changed.
Note that if the pattern does not match the entire line then the scanner
will be positioned to continue reading the remainder of the current line;
and if the pattern starts in the middle of the line, then all preceding in-
put is skipped. As usual a second form of this method takes a String
representing the pattern.
You can use a scanner's hasNextLine and nextLine methods to tokenize
input a complete line at a time. The hasNextLine method returns true if
there is another line of input in this scanner. This means that between
the current position of the scanner and the end of the input there is
either a line separator or one or more other characters. The nextLine
method advances the scanner to the start of the next line and returns
all the input that was skipped, excluding the line separator itself.
Consider the example of input that is in comma-separated-value format.
This format is often used to export values from a table, where each
line in the output represents a row of the table and each value before
a comma (or a newline) represents the contents of a cell. With a fixed
number of cells per row we can process each line of input as a single
entity:
static final int CELLS = 4;
public static List<String[]> readCSVTable(Readable source)
throws IOException {
Scanner in = new Scanner(source);
List<String[]> vals = new ArrayList<String[]>();
String exp = "^(.*),(.*),(.*),(.*)";
Pattern pat = Pattern.compile(exp, Pattern.MULTILINE);
while (in.hasNextLine()) {
String line = in.findInLine(pat);
 
Search WWH ::




Custom Search