"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Reading console input

Reading console input

Published on 2024-11-08
Browse:638

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 



Execution Example:
Input: "Read Bytes"
Exit:

Enter some characters.
You entered: Read Bytes

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

Release Statement This article is reproduced at: https://dev.to/devsjavagirls/metodos-de-leitura-do-inputstream-jj5?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3