public final static Pattern CRLF = Pattern.compile("\n\r|\r\n|\n");
/**
* Iterates over the lines of input.
*
* Usage example:
* for (String s : iterate(new FileReader("system.properties")) {
* ...
* }
*
* @param in
* @return an iterable
*/
public static Iterable iterate(final Readable in) {
return iterate(in, CRLF);
}
/**
* Iterates over the lines of input.
*
* Usage example:
* for (String s : iterate(new FileReader("system.properties", "\n")) {
* ...
* }
*
* @param in
* @param delimiter
* @return
*/
public static Iterable iterate(final Readable in, String delimiter) {
return iterate(in, Pattern.compile(delimiter));
}
/**
* Iterates over the lines of input.
*
* Usage example:
* for (String s : iterate(new FileReader("system.properties", Readables.CRLF)) {
* ...
* }
*
* @param in
* @param delimiter
* @return
*/
public static Iterable iterate(final Readable in, final Pattern delimiter) {
return new Iterable() {
@Override
public Iterator iterator() {
return new Scanner(in).useDelimiter(delimiter);
}};
}
решает вопрос
/**
* Iterates over a LineNumberReader
* Usage:
* LineNumberReader r = new LineNumberReader(new InputStreamReader(new FileInputStream("system.properties")));
* for (String line : r) {
* ...
* }
* @param in the source
* @return an iterable that scans over the lines of the source
* @throws IOException when it cannot read the first line
* @throws RuntimeException when it cannot read further down the stream
*/
public static Iterable<String> iterate(final LineNumberReader in) throws IOException {
final String first = in.readLine();
return new Iterable<String>() {
@Override
public Iterator iterator() {
return new Iterator() {
String current = first;
@Override
public boolean hasNext() {
return current != null;
}
@Override
public String next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
try {
return current;
} finally {
try {
current = in.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}};
}