org.davidmoten.kool.internal.operators.stream.FromReader Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of kool Show documentation
Show all versions of kool Show documentation
Streaming library supporting reuse and many operators
package org.davidmoten.kool.internal.operators.stream;
import java.io.IOException;
import java.io.Reader;
import org.davidmoten.kool.Stream;
import org.davidmoten.kool.StreamIterator;
import org.davidmoten.kool.internal.util.Exceptions;
public final class FromReader implements Stream {
private final Reader reader;
private final int bufferSize;
public FromReader(Reader reader, int bufferSize) {
this.reader = reader;
this.bufferSize = bufferSize;
}
@Override
public StreamIterator iterator() {
return new StreamIterator() {
char[] chars = new char[bufferSize];
int n;
@Override
public boolean hasNext() {
load();
return n != -1;
}
@Override
public String next() {
load();
int len = n;
n = 0;
return new String(chars, 0, len);
}
@Override
public void dispose() {
// do nothing
}
private void load() {
if (n == 0) {
try {
n = reader.read(chars);
} catch (IOException e) {
Exceptions.rethrow(e);
return;
}
}
}
};
}
}