Java learning IO operation

Continually updated…

Preface

Variables and arrays in the program store data temporarily because they are stored in memory and have a defined scope and life cycle. The files are stored on
secondary storage devices such as disks, CDs, or tapes, and the saved data is permanent. For languages ​​that support commercial applications, file operations are very important. If you want to
read and write files , you must master the Java input and output operations. The java.io package in the JavaAPI is the classes and methods that specialize in processing input and output.

Input stream and output stream

In Java, different input sources (input devices) and output sources (output devices) are abstractly represented as streams. A stream is a sequence of data moving between input and output in a computer. A stream represents any data source object capable of generating data or a receiving end object capable of receiving data. The flow shields the details of processing data in the actual I/O device. The stream can be divided into an input stream and an output stream.

  1. Input stream: The user reads data from the input stream. The input stream can be any serialized data source, such as a keyboard, disk file, or remote computer.
  2. Output stream: When a user writes data to a device, this stream is called an output stream. The output stream can be any device that can transmit byte sequences, such as a file on a hard disk, a telephone line connected to the network, or a display.

Note: The stream can only display characters but not output images.

The Java.io package supports two types of streams: a byte stream containing bytes and a character stream containing character data (Character stream). In addition, there is a binary stream containing binary data (Binary stream).
1. Binary stream

A stream in which data is written in the form of a series of bytes identical to those in memory. No data conversion can be performed during transmission. The binary stream in Java is the data stream. Binary values ​​are just written in byte sequence. The binary stream is handled by the DataInput interface and the DataOutput interface.
2. Byte stream

Is each byte of the byte stream ASCII, representing a character. The output is in the form of ASCII code, which corresponds to the characters of the ASCII code one-to-one, and one byte represents one ASCII code character. Therefore, it is beneficial to process the characters of ASCII code, and it is also convenient to output the characters of ASCII code. No conversion process occurs when writing characters to the byte stream or reading characters from the byte stream.

The byte stream is processed by InputStream and OutputStream ,
3. Character stream

The character stream converts the data in the memory into a Unicode code, and a Unicode is composed of two bytes. The character stream is used to store and retrieve text files, as well as to read text files generated in non-Java languages. All data in binary numerical form must first be converted into text form before being written into the character stream. When writing the character string to the stream in the form of character data. When reading a string, the data in the stream is converted from the representation of the local computer (local machine character encoding) back to Unicode. When writing a character stream, the character is converted from the Unicode code to the local machine character encoding representation of the character. The character stream is processed by Reader and Writer .

The following is a class hierarchy diagram describing the input stream and output stream:
Insert picture description here

Standard stream

When starting to run an application, the system will automatically create 3 stream objects

  1. System.in : Standard input stream object, which enables a program to receive information input from the keyboard.
  2. System.out: Standard output stream object, which enables a program to output information to the display screen.
  3. System.err: Standard error stream object, which enables a program to output error information to the display.

The so-called Console I/O, as far as the operating system is concerned, is data input and output through the command prompt window.

The default input location of the standard input stream is Console, which is the command prompt window of the operating system. Usually for the keyboard, a program can receive the information entered from the keyboard. Encapsulated by the in member of the System class, it has an InputStream type.

The default output location of the standard output stream is Console, which is the command prompt window of the operating system. Usually for command line output, a program can output information to the display. Encapsulated by the out member of the System class, it has a PrintStream type.

The default input location of the standard error output stream is Console, which is the command prompt window of the operating system. Usually the error information is mapped to the command line output so that a program can output error information to the display. Encapsulated by the err member of the System class, it has the PrintStream type.

The input and output
of the console For the input and output of the console, please refer to my other blog post
https://blog.csdn.net/dypnlw/article/details/80241897

The following will describe in detail the classes and methods corresponding to the Java.io package in the byte stream and the character stream.

Byte stream

If you want to read and write 8-bit bytes, the program should use byte streams, which are the lower classes of InputStream and OutputStream.

Class name description
BufferedInputStream Buffered input stream
BufferedOutputStream Buffered output stream
ByteArrayInputStream Input stream read from byte array
ByteArrayOutputStream Output stream written to byte array
DataInputStream Contains an input stream that reads Java standard data types
DataOutputStream Contains an output stream for writing Java standard data type methods
FileInputStream Read the input stream of the file
FileOutputStream Write file output stream
FilterInputStream Implement InputStream
FilterOutputStream Implement OutputStream
InputStream Abstract class describing stream input
OutputStream Abstract class describing stream output
PipedInputStream Input pipeline
PipedOutputStream Output pipeline
PrintStream Contains the output stream of print() and println()
PushbackInputStream Support the input stream that returns a byte of single byte "unget" to the input stream
RandomAccessFile Support random file input/output
SequenceInputStream An input stream composed of two or more sequentially read input streams

InputStream class

method description
int available() Returns the estimated number of bytes that can be read (or skipped) from this input stream by the next method call on this input stream without blocking.
void close() Close this input stream and release all system resources associated with the stream.
void mark(int readlimit) Mark the current position in this input stream.
boolean markSupported() Test whether this input stream supports the mark and reset methods.
abstract int read() Read the next byte of data from the input stream.
int read(byte[] b) Read a certain number of bytes from the input stream and store them in the buffer array b.
int read(byte[] b, int off, int len) Read up to len data bytes from the input stream into the byte array.
void reset() Reposition this stream to the position where the mark method was last called on this input stream.
long skip(long n) Skip and discard n bytes of data in this input stream.

OutputStream类

method description
void close() Close this output stream and release all system resources related to this stream.
void flush() Flush this output stream and force all buffered output bytes to be written out.
void write(byte[] b) Write b.length bytes from the specified byte array to this output stream.
void write(byte[] b, int off, int len) 将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此输出流。
abstract void write(int b) 将指定的字节写入此输出流。

FileInputStream类
Insert picture description here
FileOutputStream类
Insert picture description here
其他子类API说明详参:http://tool.oschina.net/apidocs/apidoc?api=jdk-zh

文件按字节流的方式拷贝:

package JavaReview.FileIO;
import java.io.*;
//文件按字节流的方式拷贝
public class CopyFileByte {
    public static void main(String args[]) throws IOException
    {
        FileInputStream in = null;
        FileOutputStream out = null;
        try {
            in = new FileInputStream("D:\\IDEA_Pro\\JavaPro\\src\\JavaReview\\FileIO\\input.txt");
            out = new FileOutputStream("D:\\IDEA_Pro\\JavaPro\\src\\JavaReview\\FileIO\\output.txt");
            int c;
            //read()方法读到文件末尾时,返回-1
            while ((c = in.read()) != -1) {
                out.write(c);
            }
        }finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }
}

例1中,上面使用的是文件名来创建FileInoutStream和FileOutputStream,实际上可以还可以使用文件对象来创建输入输出流。字节流的每次操作都是一个数据单位——字节,假如input.txt文件中包含 Hello world ,那么它将复制完“H”之后,再复制“e”,接着就是“l”,如此类推直到其结束。in.read()每次从输入流中读取一个字节,如果达到文件末尾就返回-1。使用完了,还要关闭这些字节流,调用close()方法。

File inFile = new File("D:\\IDEA_Pro\\JavaPro\\src\\JavaReview\\FileIO\\input.txt");
File outFile = new File("D:\\IDEA_Pro\\JavaPro\\src\\JavaReview\\FileIO\\output.txt");

FileInputStream in = new FileInputStream(inFile);
FileOutputStream out = new FileOutputStream(outFile);

字符流

Reader类和Writer类的下层类

类名 含义
BufferedReader 缓冲输入字符流
BufferedWriter 缓冲输出字符流
CharArrayReader 从字符数组读取数据的输入流
CharArrayWriter 向字符数组写数据的输出流
FileReader 读取文件的输入流
FileWriter 写文件的输出流
FilterReader 过滤读
FilterWriter 过滤写
InputStreamReader 把字节转换成字符的输入流
LineNumberReader 计算行数的输入流
OutputStreamWriter 把字符转换成字节的输出流
PipedReader 输入管道
PipedWriter 输出管道
PrintWriter 包含print( )和println( )的输出流
PushbackReader 允许字符返回到输入流的输入流
Reader 描述字符流输入的抽象类
StringReader 读取字符串的输入流
StringWriter Write the output stream of the string
Writer Abstract class describing character stream output

Similar to bytes, the key methods read() and write() are also defined in the abstract classes of characters Reader and Writer, which read and write characters respectively. Both methods are also abstract methods and are overloaded by subclasses.

Reader class
Insert picture description here
Writer class
Insert picture description here
API reference links for other subclasses: http://tool.oschina.net/apidocs/apidoc?api=jdk-zh
Example code:

package JavaReview.FileIO;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class CopyFileCharacter {
    public static void main(String[] args) throws IOException {
        FileReader in=null;
        FileWriter out=null;
        try {
            in=new FileReader("D:\\IDEA_Pro\\JavaPro\\src\\JavaReview\\FileIO\\input.txt");
            out=new FileWriter("D:\\IDEA_Pro\\JavaPro\\src\\JavaReview\\FileIO\\output.txt");

            int c;
            while((c=in.read())!=-1) {
                out.write(c);
            }
        }finally {
            if (in!=null){
                in.close();
            }
            if(out!=null){
                out.close();
            }
        }
    }
}

Comparison of byte stream and character stream

  1. The character stream class ends with Reader and Writer, and the byte stream class ends with Stream.
  2. The class level of the character stream basically corresponds to the level of the byte stream.
  3. Use InputStreamReader class and OutputStreamWriter class in Java to convert between character stream and byte stream.

Buffer
In the actual writing of input and output code, BufferWriter or BufferReader are often used. The purpose of this is to use the buffer to add the data that is read or written to the buffer. When the buffer is full Always perform a read or write operation, so that the efficiency of the program can be effectively improved.

Guess you like

Origin blog.csdn.net/dypnlw/article/details/82760268