Read bytes from InputStream until CR. - Java java.io

Java examples for java.io:InputStream Read

Description

Read bytes from InputStream until CR.

Demo Code

/*//ww  w  .j  ava  2s  .com
 *  Copyright 2006 Goran Ehrsson.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
//package com.java2s;
import java.io.IOException;
import java.io.InputStream;

public class Main {
    private static final int BUF_LENGTH = 256;

    /**
     * Read bytes until CR.
     * @param is the input stream to read bytes from.
     * @return return a byte array up to but not including the NL or CR.
     * @throws java.io.IOException if the read operation fails.
     */
    public static byte[] readLine(InputStream is) throws IOException {
        byte[] inputBuffer = new byte[BUF_LENGTH];
        int idx = 0;
        int character;
        while ((character = is.read()) != -1) {
            if (character == '\r') {
                break;
            }
            if (idx >= BUF_LENGTH) {
                // Invalid input, throw away this line.
                System.err.println("Invalid input");
                while (is.read() != -1) {
                    // Throw away.
                }
                return new byte[0];
            }
            inputBuffer[idx++] = (byte) character;
        }

        /*
         * Remove trailing CR/NL
         */
        if (idx > 0) {
            while (--idx != -1) {
                if (inputBuffer[idx] != 10 && inputBuffer[idx] != 13) {
                    break;
                }
            }
            ++idx;
        }
        byte[] input = new byte[idx];
        System.arraycopy(inputBuffer, 0, input, 0, idx);

        return input;
    }
}

Related Tutorials