preface
This is the 11th day of my participation in the First Challenge 2022
In the process of software development, we can find that almost all applications are inseparable from the input and output of information, such as reading data from the keyboard, obtaining data from the file, storing data into the file and so on. In these cases, input and output processing will be involved, which is related to the IO flow of Java. I/O streams may be unknown to many partners (some partners even see I/O streams will actively escape), so today let’s talk about the basic Java I/O streams, so that you are not afraid of IO from now on.
Basic Java IO streams
First let’s take a look at the concept of IO stream (following content from Baidu ๐)
Flow is an abstract concept that represents the unstructured transfer of data. Input and output are streamed, and data is treated as an unstructured byte order or sequence of characters. The operation of getting data from a stream is called an extract operation, while the operation of adding data to a stream is called an insert operation. The stream used for input and output operations is called an IO stream. In other words, an IO stream is a stream of input and output.
Baidu gives the basic concept may be some difficult to understand, so big smart is still adhering to the “trivial problems will be obscene solution” purpose to give you small partners with plain words about IO flow.
Let’s take a simple example: when we use a kettle to pour water into a cup, the water in the kettle can not suddenly run into the cup, but needs a process of pouring water. The process is a continuous one. Back on the computer, we need to transfer the data from the hard drive to memory for processing, but due to transmission bandwidth and other limitations, the data from the hard drive cannot be transferred to memory immediately. It has to be done bit by bit, like pouring water from a kettle into a cup. The word stream vividly describes the process of data transmission.
In the introduction, we mentioned that “almost all applications are inseparable from the input and output of information”, so what do we input or output? Yes, what we put in or out is Data (that is, an ordered set of bytes with a start and end). We call this Data a Data Stream. Let’s look at the classification of streams ๐.
โ According to the direction of data flow, we can divide it into input flow and output flow (it needs to be noted that the input and output here are for the program), the flow that reads data from other devices into memory is the input flow, and the flow that writes data from memory to other devices is the output flow. โก According to the unit of data processed, we can divide it into byte stream and character stream. The meaning of byte stream is to read (or write) one byte at a time. The meaning of a character stream is to read (write) two bytes at a time, using a character stream can correctly display Chinese (1 character = 2 bytes, a Chinese character is two bytes long). Byte stream is generally used to process images, video, audio, PPT, Word and other types of files; Character streams are used to process plain text files such as TXT files, but not non-text files such as images or videos. To sum it up, byte streams can handle all files, while character streams can only handle plain text files. (3) According to the roles of streams, we can also divide them into node flow and processing flow. Node flow refers to the flow that can read (write) data from (to) a specific IO device (such as disk, network) (directly connected to the “data source” and “destination”); A processing stream is used to connect and encapsulate an existing stream, through which data is read/written (not directly connected to the “data source” and “destination”, but connected to the existing stream). As shown in the following figure ๐
(4) Buffer flow, buffer flow is a particularly important part of many flows. Program interactions with the disk speed relative to the memory computing speed is very slow, also said program with disk interaction efficiency directly affects the application performance of high and low, in order to improve the efficiency of the program and disk interaction and the buffer flow also arises at the historic moment, the buffer flow set up a buffer in the memory, normal flow every read a child’s day, The sub-section is stored in the buffer first. When the buffer stores enough sub-sections, it can interact with the disk. In other words, under the condition that the total amount of data remains unchanged, the number of interactions is reduced by increasing the amount of data for each interaction, thus improving the interaction efficiency. For example, we will always find a pickup truck when moving to help us move, we first need to move my luggage into the pickup truck, such as small transport trucks full of cars into a new home later, we use truck to reduce the number of our old home and home back and forth, so as to improve the removal efficiency of the pickup is buffer, our own common flow, Your own luggage is a sub-section of the normal stream read. (If this depends on two legs to carry luggage to and from the new home and old home, estimated to move three days can not finish ๐)P.S. Using buffered streams does not necessarily make your application run more efficiently; it is a matter of case by case
Cui Hua ~ on the code!
With all the theoretical stuff mentioned above, let’s look at how to use Java IO streams in code.
Byte stream
import java.io.*;
/** * The application of IO streams *@description: IODemo
* @author: Zhuang Ba. Liziye *@create: the 2022-01-19 it * * /
public class IODemo {
// The string to write to
private static String text = "I'm eating fried chicken in People's Square.";
public static void main(String[] args) throws IOException {
File file = new File("G:/IODemo.txt");
write(file);
String result = read(file);
System.out.println("result = " + result);
}
public static void write(File file) throws IOException {
OutputStream os = new FileOutputStream(file, true);
// Write to the file
os.write(text.getBytes());
/ / close the flow
os.close();
}
public static String read(File file) throws IOException {
InputStream in = new FileInputStream(file);
// How many bytes are taken at a time
byte[] bytes = new byte[1024];
// An array of bytes used to receive reads
StringBuilder sb = new StringBuilder();
// The length of the byte array read is -1, indicating no data
int length = 0;
// loop to fetch data
while((length = in.read(bytes)) ! = -1) {
// Convert what is read to a string
sb.append(new String(bytes, 0, length));
}
/ / close the flow
in.close();
returnsb.toString(); }}Copy the code
Buffer byte stream
import java.io.*;
/** * The application of IO streams *@description: IODemo
* @author: Zhuang Ba. Liziye *@create: the 2022-01-19 it * * /
public class IODemo {
/** * The text to be written */
private static String text = "Bought another fried chicken ~ I am eating fried chicken in people's Square ~";
public static void main(String[] args) throws IOException {
File file = new File("G:/IODemo.txt");
write(file);
String result = read(file);
System.out.println("result = " + result);
}
public static void write(File file) throws IOException {
// Buffer byte stream, improve efficiency
BufferedOutputStream bis = new BufferedOutputStream(new FileOutputStream(file, true));
// Write to the file
bis.write(text.getBytes());
/ / close the flow
bis.close();
}
public static String read(File file) throws IOException {
BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file));
// How many bytes are taken at a time
byte[] bytes = new byte[1024];
// An array of bytes used to receive reads
StringBuilder sb = new StringBuilder();
// The length of the byte array read is -1, indicating no data
int length = 0;
// loop to fetch data
while((length = fis.read(bytes)) ! = -1) {
// Convert what is read to a string
sb.append(new String(bytes, 0, length));
}
/ / close the flow
fis.close();
returnsb.toString(); }}Copy the code
Characters of the flow
import java.io.*;
/** * The application of IO streams *@description: IODemo
* @author: Zhuang Ba. Liziye *@create: the 2022-01-19 it * * /
public class IODemo {
/** * The text to be written */
private static String text = "Bought the third fried chicken ~ I ate fried chicken in people's Square ~";
public static void main(String[] args) throws IOException {
File file = new File("G:/IODemo.txt");
write(file);
String result = read(file);
System.out.println("result = " + result);
}
public static void write(File file) throws IOException {
// OutputStreamWriter can display the specified character set, otherwise use the default character set
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(file, true), "UTF-8");
osw.write(text);
osw.close();
}
public static String read(File file) throws IOException {
InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "UTF-8");
// String array: How many characters are read at a time
char[] chars = new char[1024];
// Append the character array to StringBuilder each time it is read
StringBuilder sb = new StringBuilder();
// The length of the character array read is -1, indicating no data
int length = 0;
// loop to fetch data
while((length = isr.read(chars)) ! = -1) {
// Convert what is read to a string
sb.append(chars, 0, length);
}
/ / close the flow
isr.close();
returnsb.toString(); }}Copy the code
Buffered character stream
import java.io.*;
/** * The application of IO streams *@description: IODemo
* @author: Zhuang Ba. Liziye *@create: the 2022-01-19 it * * /
public class IODemo {
/** * The text to be written */
private static String text = "Bought a fourth fried chicken ~ I ate fried chicken in people's Square ~";
public static void main(String[] args) throws IOException {
File file = new File("G:/IODemo.txt");
write(file);
String result = read(file);
System.out.println("result = " + result);
}
public static void write(File file) throws IOException {
BufferedWriter bw = new BufferedWriter(new FileWriter(file, true));
bw.write(text);
bw.close();
}
public static String read(File file) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(file));
// An array of bytes used to receive reads
StringBuilder sb = new StringBuilder();
// Read data in rows
String line;
// loop to fetch data
while((line = br.readLine()) ! =null) {
// Convert what is read to a string
sb.append(line);
}
/ / close the flow
br.close();
returnsb.toString(); }}Copy the code
Common methods used in IO streams
There are many methods in IO stream, want to learn all the methods are still a little difficult, finally sorted out the IO stream common methods for your reference and learning ๐
Byte InputStream InputStream
Int read() : Reads a single subsection.
Int read(byte[] b) : Reads multiple bytes into an array. Int read(byte[] b, int off, int len) : Reads data of length len, places the read data from the subscript OFF of array B, and returns the number of bytes read. Void close() : closes the data stream. Int available() : Returns the current number of bytes that can be read from the data stream. Long skip(long L) : skip a specified number of bytes in the data stream. The return value represents the number of bytes actually skipped.
Byte OutputStream OutputStream
Void write(int I) : Writes byte I to the data stream. It outputs only the minimum 8 bits of the argument read in. This method is abstract and needs to be implemented in its output stream subclass before it can be used.
Void write(byte[] b) : writes all bytes in array B to the data stream. Void write(byte[] b, int off, int len) : Writes len bytes from array B starting with the subscript off to the data stream. It starts at b[off] and ends at B [off + len-1]. Void close() : closes the output stream. Before closing the output stream, refresh it. Void flush() : Flushes the stream and forces out all buffered output bytes.
Character input stream InputStreamReader
Int read() : Reads a single character.
Abstract int read(char[] cbuf, int off, int len) : Reads len of length data, places the read data from the cbuf at the subscript OFF position, and returns the number of bytes read. Long skip(long n) : skip a specified number of bytes in the data stream. The return value represents the number of bytes actually skipped. Abstract void close() : Closes the data stream.Copy the code
Character output stream OutputStreamWriter
Void write(char[] cbuf) : Writes an array of characters to the data stream
Abstract void write(char[] cbuf, int off, int len) : Writes len bytes from the character array Cbuf starting with the subscript OFF to the data stream. Start from b[off] and end from B [off + len-1] void write(int c) : Write a single character void write(String STR) : Void write(String STR, int off, int len) : Write a part of the String. Writer Append (char c) : Writerwriterappend (CharSequence CSQ) : Writerappend (CharSequence CSQ, int start, int end) : writerAppend (CharSequence CSQ, int start, int end) : writerAppend (CharSequence CSQ, int start, int end) : Appendable abstract void close() : close the stream, but flush it first. Abstract void Flush () : flush the buffer of the streamCopy the code
summary
My experience is limited, some places may not be particularly in place, if you think of any questions when reading, welcome to leave a message in the comments section, we will discuss one by one ๐
Please take a thumbs up and a follow (โฟโกโฟโก) for this article ~ a crab (โ’โก’โ)
If there are mistakes in the article, welcome to comment correction; If you have a better, more unique understanding, you are welcome to leave your valuable ideas in the comments area.
When you are struck, remember your preciousness and resist malice;
When you are confused, believe that your precious, put aside gossip; Love what you love, do what you do, listen to your heart and ask nothing