System.in

A outra variável de System associada aos dispositivos padronizados corresponde à entrada padrão:
in
public static final InputStream in
	  
The "standard" input stream. This stream is already open and ready to supply input data. Typically this stream corresponds to keyboard input or another input source specified by the host environment or user.

Da mesma forma que out, a variável é estática, pública e final. No entanto, esse é um objeto da classe java.io.InputStream, uma classe abstrata que especifica, entre vários métodos, o método read():
read
 public abstract int read() throws IOException
	  
Reads the next byte of data from this input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

A subclass must provide an implementation of this method.

Returns:
the next byte of data, or -1 if the end of the stream is reached.
Throws: IOException
if an I/O error occurs.
read
 public int read(byte b[]) throws IOException
	  
Reads up to b.length bytes of data from this input stream into an array of bytes.

Parameters:
b - the buffer into which the data is read.
Returns:
the total number of bytes read into the buffer, or -1 is there is no more data because the end of the stream has been reached.
Throws: IOException
if an I/O error occurs.

No entanto, esse método de entrada é muito primitivo, sendo dificilmente usado dessa maneira para obter entradas de um usuário através do teclado. A forma usual para realizar essa tarefa envolve o uso de outras funcionalidades de entrada e saída oferecidas por Java, em particular o uso de buffers.

Assim, para ter um objeto associado ao dispositivo padrão de entrada que permite ler uma linha completa através do teclado, a seguinte fórmula é utilizada:

 BufferedReader in
   = new BufferedReader(new InputStreamReader(System.in));

Objetos da classe BufferedReader oferecem um método readLine() que retorna uma string de texto, que neste exemplo seria lida a partir do teclado.


© Ivan Luiz Marques Ricarte
DCA/FEEC/UNICAMP

Last modified: Mon Jul 3 12:06:27 EST 2000