Home >Java >javaTutorial >Reading console input

Reading console input

DDD
DDDOriginal
2024-11-03 16:14:30632browse

Lendo a entrada do console

InputStream Reading Methods:

  • read(): Allows you to read bytes directly from the stream.
  • Three versions of read():
  • int read(): Reads a single byte and returns -1 at the end of the stream.
  • int read(byte data[]): Reads bytes until the data array is filled, the end of the stream is reached or an error occurs. Returns the number of bytes read, or -1 if the end of the stream is reached.
  • int read(byte data[], int start, int max): Reads up to max bytes in the data array starting from the start index. Returns the number of bytes read, or -1 if the end of the stream is reached.
  • Exceptions: All versions of read() can throw an IOException in case of an error.

Using System.in for Reading:
Reading Console Input: System.in is used as input stream, where pressing "ENTER" indicates the end of the input stream.

ReadBytes Code Example:
Functionality: The program reads a byte array from the console and displays the entered characters.
Code Structure:
data[]: 10-byte array to store the input.
System.in.read(data): Reads the characters typed into the console and stores them in data.
Display Loop: Iterates over data[] to convert each byte to character and display them.

Example Code:

import java.io.*;

class ReadBytes {
    public static void main(String args[]) throws IOException {
        byte data[] = new byte[10];
        System.out.println("Enter some characters.");
        System.in.read(data); // Lê o array de bytes
        System.out.print("You entered: ");
        for (int i = 0; i < data.length; i++)
            System.out.print((char) data[i]); // Converte e exibe cada byte como caractere
    }
}

Execution Example:
Input: "Read Bytes"
Output:

Enter some characters.
You entered: Read Bytes

This excerpt details how to use the read() methods to read keyboard data in byte format, illustrating the basic use of System.in for console input and demonstrating direct manipulation of bytes in an array.

The above is the detailed content of Reading console input. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn