ch.software_atelier.simpleflex.UntilNewlineReader Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of simpleflex-base Show documentation
Show all versions of simpleflex-base Show documentation
Build Micro Services with pico footprint
package ch.software_atelier.simpleflex;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
*
* @author tk
*/
public class UntilNewlineReader {
private InputStream _is;
private byte[] _buffer;
private int _inBufferStart = -1;
private int _inBufferSize = -1;
public UntilNewlineReader(InputStream is, int buffersize){
_is = is;
_buffer = new byte[buffersize];
}
public byte[] read()throws IOException{
byte[] result = null;
try(ByteArrayOutputStream os = new ByteArrayOutputStream();){
if (_inBufferStart>=0 && _inBufferSize >= 0){
if( writeUntilNewline(os, _inBufferStart, _inBufferSize) ){
// found a newline in buffer
result = os.toByteArray();
return result;
}
else{
_inBufferStart = -1;
_inBufferSize = -1;
}
}
int length = 0;
while ( (length=_is.read(_buffer))!=-1){
if( writeUntilNewline(os, 0, length) ){
// found a newline in buffer
result = os.toByteArray();
return result;
}
}
result = os.toByteArray();
}
return result;
}
private boolean writeUntilNewline(OutputStream os, int from, int size) throws IOException{
if (size==0){
return false;
}
int i;
boolean newlineFound = false;
for (i=from;i