Page 1 of 1

Improved ReadLine

Posted: Thu Dec 10, 2009 6:17 pm
by jdalbey
The sample ReadLn() method doesn't really read an entire line of data. It just reads the number of bytes specified in the parameter. Here is an improved version that actually reads an entire line.

Code: Select all

    /** Return a line of input from System.in,
     *  or null if EOF.
     */
    static String ReadLn () 
    {
        int inbyte = -1;
        StringBuffer line = new StringBuffer();
    
        try
        {
            inbyte = System.in.read();
            while ((inbyte >= 0) && (inbyte != '\n'))
            {
                line.append((char) inbyte);
                inbyte = System.in.read();
            }
        }
        catch (IOException e)
        {
            return (null);
        }

        if ((inbyte < 0) && (line.length() == 0)) return (null);  // eof
        return line.toString();
    }