All Downloads are FREE. Search and download functionalities are using the official Maven repository.

ch.software_atelier.simpleflex.UntilNewlineReader Maven / Gradle / Ivy

There is a newer version: 2.2.2
Show newest version
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




© 2015 - 2024 Weber Informatics LLC | Privacy Policy