
com.daredayo.util.io.SnapShotReader Maven / Gradle / Ivy
package com.daredayo.util.io;
import java.io.IOException;
import java.io.Reader;
import java.nio.CharBuffer;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.IOUtils;
import com.daredayo.util.SnapShot;
/**
* this is specialized for CSVReader to get snapshot that consumed by reader#read()
*/
public class SnapShotReader extends Reader implements SnapShot {
Reader reader;
List snapshot = new ArrayList<>();
boolean doSnapShot = false;
public SnapShotReader(Reader reader) {
super();
this.reader = reader;
}
//reader
public int read() throws IOException{
int read = reader.read();
if(doSnapShot && read != -1){
snapshot.add((char)read);
}
return read;
}
public String toString() {
return reader.toString();
}
@Override
public void close() {
IOUtils.closeQuietly(reader);
reader=null;
}
//snapshot
public void start(){
snapshot.clear();
doSnapShot = true;
}
public List stop(){
doSnapShot = false;
return snapshot;
}
public List getSnapShot(){
return snapshot;
}
@Override
public int read(char[] cbuf, int off, int len) throws IOException {
int read = reader.read(cbuf, off, len);
if(doSnapShot){
for(int i = 0 ; i < read ; i++){
snapshot.add(cbuf[i + off]);
}
}
return read;
}
@Override
public int read(CharBuffer target) throws IOException {
int read = reader.read(target);
if(doSnapShot){
for(int i = 0 ; i < read ; i++){
snapshot.add(target.charAt(i));
}
}
return read;
}
@Override
public int read(char[] cbuf) throws IOException {
return read(cbuf ,0 ,cbuf.length);
}
public boolean isClosed(){
return reader == null;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy