Java BufferedReader Read Line readLine(BufferedReader br, int maxlen)

Here you can find the source of readLine(BufferedReader br, int maxlen)

Description

Reads the next non-empty line of text from a buffered reader, up to a given number of characters.

License

Apache License

Parameter

Parameter Description
br The BufferedReader to get a line from.
maxlen The maximum length of string to read from the line.

Return

A line of text, not including any line-termination characters, or null if the end of stream has been reached. An empty string will indicate that the maxlen number of characters was reached before any text could be read.

Declaration

public static final String readLine(BufferedReader br, int maxlen) throws IOException 

Method Source Code


//package com.java2s;
/*/*from   w  w w . j av  a 2 s . c  om*/
 * Copyright 2011 Paula Gearon.
 *
 * 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.
 */

import java.io.BufferedReader;
import java.io.IOException;

public class Main {
    /**
     * Reads the next non-empty line of text from a buffered reader, up to a given
     * number of characters.
     * 
     * @param br The BufferedReader to get a line from.
     * @param maxlen The maximum length of string to read from the line.
     * @return A line of text, not including any line-termination characters,
     *         or null if the end of stream has been reached. An empty string will
     *         indicate that the maxlen number of characters was reached before any
     *         text could be read. 
     */
    public static final String readLine(BufferedReader br, int maxlen) throws IOException {
        StringBuilder s = new StringBuilder();

        for (int i = 0; i < maxlen; i++) {
            int c = br.read();
            if (c == -1) {
                if (s.length() == 0)
                    return null;
                break;
            }
            if (c == '\n' || c == '\r') {
                if (s.length() == 0)
                    continue;
                break;
            }
            s.appendCodePoint(c);
        }
        return s.toString();
    }
}

Related

  1. readLine()
  2. readLine()
  3. readLine()
  4. readLine()
  5. readLine(BufferedReader br)
  6. readLine(BufferedReader in)
  7. readLine(BufferedReader in)
  8. readline(BufferedReader in, BufferedReader err)
  9. readLine(BufferedReader input)