JAVA—data input and output

1. What is input stream and output stream

In Java, all input and output are treated as streams. A stream is a collection of data arranged in a certain order. For example, data input from the keyboard or files, data output to the display or files, etc. can be regarded as individual data streams.
When inputting data, a program opens a stream (file or memory, etc.) on the data source, and then inputs the data in this stream in order. Such a stream is called an input stream, as shown in the upper figure of Figure 7-1.
When outputting data, a program can open a destination stream (such as a file or memory, etc.), and then send it in order
A destination outputs data, and such a stream is called an output stream, as shown in the lower figure of Figure 7-1.
The direction of input stream and output stream can also be understood in this way, they are based on the program. A stream that inputs data into a program is defined as an input stream, and a stream that outputs data from a program is called an output stream. Therefore, we refer to inputting data from the input stream to the program as reading data (read), and outputting data from the program to the output stream as writing data (write).

2. Byte stream and character stream

The input/output stream can be divided into two types according to the type of data processed: one is byte stream, and the other is character stream. A byte stream means reading/writing data in the form of bytes, and a character stream means reading/writing data in the form of characters.
In Java, the abstract classes InputStream and OutputStream and their derived subclasses are used to process the input and output of byte streams, and the abstract classes Reader and Writer and their derived subclasses are used to process the input and output of character streams.
In addition, the system also provides the System class for standard input and output, and the Scanner class for parsing various types of data (such as integers, floating-point numbers, strings, etc.).
Please note that although Java essentially divides the input/output stream into a byte stream and a character stream, this does not mean that we can only input/output data in these two lowest-level forms. In fact, we can input/output various types of data by calling constructors and member methods of many classes.

3. Standard input/output class System

Whether it is debugging a program, or when the program debugging is successfully delivered, we often need to input some data into the program through the keyboard, and display some program running status information or data processing results through the display. Therefore, basic input/output functions are used very frequently. To this end, Java specifically provides a System class to help users deal with basic input/output issues. For this, we have used it many times in the previous program, as shown in the following statement:
//Declare a Scanner class object inStatus whose content comes from keyboard input (System.in)
Scanner inStatus = new Scanner(System.in);
// output string and variable value
System.out.println(“The tax amount that the taxpayer needs to pay is ” + tax + “¥”);
The System class belongs to the java.lang package, and it provides some methods that can be used to terminate the currently running Java virtual machine, run the garbage collector, and obtain the value of the specified environment variable.
The System class has two very useful static member constants in and out, which respectively represent the standard input device (usually a keyboard) and standard output device (usually a display), and their functions are as follows:
① in: The declaration form is public static final InputStream in. When using, we can use the System.in.read() method to read byte data from the keyboard. However, System.in is more often used as a parameter of other objects, indicating that the data entered by the keyboard is used as its data source. For example, Scanner in=new Scanner(System.in); the statement means to create a Scanner class object in, whose content comes from the data entered by the keyboard.

②out: The declaration form is public static final PrintStream out. When in use, we can use System.out.print(“string”); statement and System.out.println(“string”); statement to display various types of data on the display, such as string, numeric data , Boolean data, character data, etc., and the former means to display data in the current line, and the latter means to display data in the current line and wrap.
Kind tips
The PrintStream class is a subclass of FilterOutputStrean, a subclass of the byte output stream class OutputStream, and various types of data can be output by using its printO method and println method. Since both in and out are static member constants, they can be called directly through the form of “class name, member variable point member constant name”.

package com.sxt;

import java.io.IOException;


public class Text {
    public static void main(String[] args ) throws IOException{
   int b;
   System.out.println("Please enter data:");
   while((char)(b=System.in.read())!='N')
   {
       System.out.print((char)b);
   }
    }}

It can be concluded from the above code: (1) The system will wait after encountering the read() method, and only read characters one by one when the line is changed. This is called blocking in Java, and it is actually waiting.

(2) The read() method reads characters one by one, so it cannot recognize integers, floating point numbers, strings, etc. entered by the user.

(3) The read() method reads characters by character, so it can only recognize single-byte characters (such as English letters, numbers, and English punctuation marks, etc.), and cannot recognize double-byte Chinese characters.

4. Character and character input/output stream class

The abstract classes InputStream and OutputStream and their derived subclasses are used to process the input and output of byte streams, and the abstract classes Reader and Wrtite and their derived subclasses are used to process the input and output of character streams.

(1) Byte input stream class InputStream

The byte input stream class (InputStream) is used to read data from the data source in byte form, and it is the parent class of all byte input stream classes. In addition, since this class is an abstract class, it cannot be instantiated, that is, objects cannot be created based on this class.
Although abstract classes cannot be used to create objects, they can be used to declare objects. For example, in the System class, the system uses the public static final InputStream in; statement to declare an InputStream class object in.
In the above code, we have used the System.in.read() statement to read the data entered from the keyboard. At this time, in has been instantiated as an object of a certain subclass of the InputStream class, so the readO method called at this time is actually the read() method of a certain subclass.
The main derived subclasses of the InputStream class include: FileInputStream (read the data in the file by byte), BufferedInputStream (save the data read in by byte to the buffer), etc.

Its hierarchy is as follows:

InputStream
ByteArrayInputStream

FileInputStream

FilterInputStream
BufferedInputStream

DatalnputStream

LineNumberInputStream

PushbackInputStream

ObjectInputStream

PipedInputStream

SequenceInputStream

StringBufferInputStream

Among the above subclasses, BufferInputStream is a very useful class, which can buffer the input data, thereby improving the efficiency of data input. Its construction method is: public BufferedInputStream(InputStream in). Among them, in can be a file input stream or a keyboard input stream. This class has the following main methods:
public void close(): Closes this input stream and releases all system resources associated with this stream.
public abstract int read(): Reads the next byte of data from the input stream. Its return value is an integer,
Returns -1 if the end of the stream is reached.
When inputting data from the keyboard (that is, the data source is System.in), the read() method is blocked until the Enter key is pressed.
If you press the [Ctrl + Z] key combination, it means that the input stream ends. At this time, the input content of this line is ignored, and the return value of read() is -1.
When reading a file (the data source at this time is a FileInputStream class object), if the end of the file is reached, the return value of the readO method is -1.
public int read(byte[] b): Store the content read from the input stream in the byte array b. Its return value is the number of bytes read. Returns -1 if no more data is available because the end of the stream has been reached.

(2) Byte output stream class OutputStream

The character output stream class OutputStream is used to write data to the destination in byte form, and its main derived subclasses include: FileOutputStream (to write data to a file), PrintStream (to output various types of data, such as integers, floating point numbers, Characters, strings, Boolean values, etc., its main methods are print () and println ()) and so on. Its hierarchy is as follows:
OutputStream
ByteArrayOutputStream
FileOutputStream
FilterOutputStream
BufferedOutputStream
DataOutputStream
PrintStream
ObjectOutputStream
PipedOutputStream
Among the above subclasses, BufferedOutputStream is a very useful class, which can buffer the output data, thereby improving the efficiency of data output. The constructor of this class is as follows:
public BufferedOutputStream(OutputStream out)
It represents the creation of a new buffered output stream to write data to the specified underlying output stream.
-> public void close(): Closes this buffered output stream and releases all system resources related to this stream.

-> public void write(int b): Writes the specified byte to this buffered output stream.

->public void write(byte[] b): Writes b.length bytes to this buffered output stream.

(3). Character input stream class Reader

The character input stream class Reader is used to read data from the data source in the form of characters, and its main derived subclasses include InputStreamReader (read byte data and decode it into characters), FileReader (used to read the contents of character files) , BufferedReader (read text from the character input stream, buffer each character, so as to realize the efficient reading of characters, arrays and lines), etc. Its hierarchy is as follows:
reader
Buffered Reader
LineNumberReader

CharArrayReader

FilterReader
Pushback Reader

InputStreamReader

FileReader

Piped Reader

StringReader
Among them, the construction method of the InputStreamReader class is: public InputStreamReader(InputStream in);
Its main member methods are:
-> public void close0: closes the stream and releases all resources associated with it.
-> public int readO: Reads a single character.
-> public int read(charü cbuf): reads characters into an array. The return value is the number of characters read. Returns -1 if the end of the stream has been reached.

The constructor of the BufferedReader class is: public BufferedReader(Reader in), which is used to create a buffered character input stream using the default size input buffer. Its member methods are similar to InputStreamReader, except that a new readLineO method is added, and its declaration method and function are as follows:
->public String readLine(): Read a text line. A line can be considered terminated by one of the following characters: newline (“\
), carriage return (\r), or carriage return followed by a newline. The return value is a string containing the content of the line and does not contain any The line terminator. Returns null if the end of the stream has been reached.

(4) Character output stream class Writer

The character output stream class Writer is used to write data to the destination in the form of characters. The Writer class is all character output
The parent class of the stream class, its main derived subclasses include OutputStreamWriter (writes characters to the output stream in bytes),
FileWriter (write character data to a file), BufferedWriter (write character data to a buffer), PrintWrie
(formatted output character data) and other subclasses. Its hierarchy is as follows:
Writer
Buffered Writer

CharArray Writer

FilterWriter
OutputStream Writer
File Writer Piped Writer
PrintWriter
String Writer
Among them, the construction method of the OutputStreamWriter class is: public OutputStreamWriter(OutputStream out);

Its main member methods include:
–> public void close(): close this stream
–>public void write(int c): Write a single character.
–>public void write(char|] cbuf): write character array.
–>public void write(String str): Write a string.
The construction method of the BufferedWriter class is public BufferedWriter(Writer out), and its main member methods include
–>public void close0: Close this stream.
–>public void write(int c): Write a single character.
–>public void write(char[]cbuf: write character array.
–>public void write(String str): Write a string.
–>public void newLine0: Write a line separator.

5. Use the Scanner class to input various types of data

The Scanner class is a simple text scanner that can parse primitive types and strings using regular expressions, I
We have used it in many of the previous programs. The Scanner class represents a text scanner that can scan characters entered from the keyboard.

The so-called regular expression refers to a single character string used to describe or match a series of character strings conforming to a certain syntax rule. In many text editors and other tools, regular expressions are often used to retrieve and/or replace text content that matches a certain pattern.

This class has a set of important methods whose meaning is as follows:
nextByte (), nextShort (), nextInt (), nextLong (), nextFloat (), nextDouble (), nextBoolean () and other methods are used to read bytes, short integers, integers, long integers, floating point numbers , double-precision floating-point numbers, Boolean values, etc.
hasNextByte(), hasNextShort(), hasNextIntO, hasNextLong(), hasNextFloat(), hasNextDouble(), hasNextBoolean() and other methods are used to determine whether the data to be read is a byte, a short integer, an integer, or a long integer type, float, double, or boolean, etc.
The nextLine() method is used to read a line of data. If the data has been read by nextByte(), nextShort() and other methods, this method is used to read the subsequent data in the current line; the hasNextLine() method is used to confirm whether there is still the next line A line of data, this method is mainly for files, and is used to judge whether the end of the file has been reached.

If you enter multiple data on one line, you can separate each data with a space.

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge Java skill treeHomepageOverview 108559 people are studying systematically