Like you who love programming!
Learn SpringBoot actual combat course https://edu.csdn.net/course/detail/31433
Learn SpringCloud introductory course https://edu.csdn.net/course/detail/31451
Preface
IO is an important part of the Java knowledge system, because we need to read data from disk or network, so that we can complete data persistence and network communication. This article will take you to understand IO flow.
IO flow classification
Classified by type of operation data:
- Byte stream
- Generally used to manipulate binary data, the unit of data is byte (video, audio, picture, exe, dll and other files)
- End with InputStream or OutputStream
- Character stream
- Generally used to manipulate text data, the unit of data is char (txt, xml, html and other files)
- End with Reader or Writer
Classified by data flow:
- Input stream
- Stream from disk file or network to Java program for reading data
- The parent class of all byte input streams is InputStream
- The parent class of all character input streams is Reader
- Output stream
- Flow from the Java program to the disk file or network for writing data
- The parent class of all byte output streams is OutputStream
- The parent class of all character output streams is Writer
File read and write
File reading
The
function of FileInputStream is to read data from a disk file or network.
Construction method:
FileInputStream(File file)
FileInputStream(String filepath)
Main method:
- int read(byte[] buffer) Read the file data and save it in the byte array. The return value is the read length-1 which means the read is completed.
- void close() close the file stream
The try-with-resource
IO stream must be closed after use, otherwise the file stream cannot be released, and the close method call should be written in finally.
In order to simplify the code of closing the stream, Java 1.7 introduces the try-with-resource syntax, which allows the resource to be automatically closed after the try-catch is completed.
grammar:
try(类 对象 = new 类()){
可能出现异常的代码
}catch(异常类型 对象){
处理异常的代码
}
Note: The closed object must implement the Closable interface, and all IO streams implement this interface.
File reading process
- Create file input stream
- Create byte array
- Call the read method in a loop to read the data and store it in the byte array
- Manipulate byte array
- Close the file stream after reading
/**
* 读取文件内容
* @param filepath
*/
public void read(String filepath){
//1、创建文件输入流
try(FileInputStream fis = new FileInputStream(filepath)) {
//2、创建byte数组
byte[] buffer = new byte[1024];
//3、循环调用read方法读取数据,存入byte数组
int len = 0;
while((len = fis.read(buffer)) != -1){
//4、操作byte数组,如果是文字将byte[]转换为String
String str = new String(buffer,0,len,"UTF-8");
System.out.println(str);
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testRead(){
read("C:/xpp/Test6.java");
}
File writing
File output stream FileOutputStream
function is: write data to disk file or network
Construction method:
FileOutputStream(File file)
FileOutputStream(String filepath)
Main method:
- write(byte[] buffer,int offset,int length) write file, offset start position, length write length
- write(byte[] buffer)
- close() close the stream
File writing steps:
- Create file output stream
- Convert string to byte array
- Call write to write file
- Close file stream
/**
* 写入磁盘文件
* @param filepath
* @param content
*/
public void write(String filepath,String content){
//1、创建文件输出流
try (FileOutputStream fos = new FileOutputStream(filepath)){
//2、将字符串转换为byte数组3、调用write写入文件
fos.write(content.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testWrite(){
write("C:/xpp/xxxx.txt","这是我要写入的内容:Hello JavaEE!");
}
Copy of files
File copying is to write data to another file while reading the file.
Ideas:
1. Create an input stream and output stream
2. Read data into the byte array through the input stream
3. At the same time, add the data in the byte array Data is written to output stream
4, loop 1, 2, 3
/**
* 复制文件
* @param source 原始文件路径
* @param target 目标文件路径
*/
public void copy(String source,String target){
//创建文件输入流、文件输出流
try(FileInputStream fis = new FileInputStream(source);
FileOutputStream fos = new FileOutputStream(target)){
//创建byte数组
byte[] buffer = new byte[1024];
int len = 0;
//循环从输入流读取数据
while((len = fis.read(buffer)) != -1){
//写入到输出流中
fos.write(buffer, 0, len);
}
}catch(Exception ex){
ex.printStackTrace();
}
System.out.println("复制完毕");
}
@Test
public void testCopy(){
copy("C:\\xpp\\InletexEMCFree.exe","C:\\xpp\\InletexEMCFree2.exe");
}
buffer
What is buffer
The premise is that the read and write speed of the memory is much higher than the read and write speed of the disk. The buffer is a piece of space in the memory, and the data read and write speed can be improved through the buffer.
Why buffer
If there is no buffering, file reading and writing are performed directly from the disk, and the speed is relatively slow; buffering is to create a space in the memory, before reading and writing a part of the data on the disk is imported into the buffer memory, and subsequent reading and writing are directly from the buffer It reduces the number of direct reads and writes from the disk, thereby improving read and write efficiency.
Buffer flow: On the basis of ordinary IO flow, add memory buffer to improve IO efficiency.
Byte buffer stream
BufferedInputStream buffered input stream
创建方法:
new BufferedInputStream(InputStream in)
new BufferedInputStream(InputStream in,int bufferSize)
Description:
- The parameter InputStream is a byte input stream. After being passed into the buffered input stream, the buffer is added.
- The parameter bufferSize can set the buffer size
BufferedOutputStream buffered output stream
创建方法:
new BufferedOutputStream(OutputStream out)
new BufferedOutputStream(OutputStream out,int bufferSize)
The following case uses JUnit to test the efficiency comparison of file copy using unbuffered stream and buffered stream:
public class TestIO {
/**
* 不使用缓冲复制文件
* @param source
* @param target
*/
public void copyWithoutBuffer(String source,String target){
System.out.println("不使用缓冲复制文件");
//创建文件输入流和输出流
try(FileInputStream in = new FileInputStream(source);
FileOutputStream out = new FileOutputStream(target)){
//定义字节数组
byte[] buffer = new byte[100];
int len = 0;
//读取数据
while((len = in.read(buffer)) != -1){
//写入数据
out.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 使用缓冲复制文件
* @param source
* @param target
*/
public void copyWithBuffer(String source,String target){
System.out.println("使用缓冲复制文件");
//创建缓冲输入流和输出流
try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(source));
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(target))) {
//定义字节数组
byte[] buffer = new byte[100];
int len = 0;
//读取数据
while ((len = in.read(buffer)) != -1) {
//写入数据
out.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void testCopyWithoutBuffer(){
copyWithoutBuffer("D:/install/jdk-8u171-windows-x64.exe","D:/jdk1.exe");
}
@Test
public void testCopyWithBuffer(){
copyWithBuffer("D:/install/jdk-8u171-windows-x64.exe","D:/jdk2.exe");
}
}
It took more than 10s to copy files without the cache, and 0.59s to use the cache, which was nearly 20 times faster.
Character stream
Streaming in char units is suitable for manipulating text data.
- The parent class of Reader character input stream
- The parent class of Writer character output stream
FileReader File Reader
Creation method:
new FileReader(String path) path是文件路径
Main method:
- int read(char[] buffer) read data into character array
- close()
FileWriter file writer
Creation method:
new FileWriter(String path) path是文件路径
Main method:
- write(char[] buffer) write character array
- write(char[] buffer,int offset,int length)
- write(String str) write string
Character buffer stream
BufferedReader
Buffered reader
creation method:
new BufferedReader(Reader reader)
Unique method:
- readLine() read a line of text
BufferedWriter
Buffered writer
creation method:
new BufferWriter(Writer writer)
Unique method:
- write(String str) write string
- newLine() insert newline
Print stream
Can control the print format during output. The
print flow is divided into:
- PrintStream byte print stream, System.out is PrintStream
- PrintWriter character printing stream
Common methods:
- print output
- println output with line break
- printf("format string", variable parameter) output with format
%s output string
%d output integer
%f output decimal
%n output newline
data flow
A high-level byte stream that can read and write data in the stream with various data types (byte\short\int\long\char\boolean\String...).
DataInputStream
Construction method:
DataInputStream(InputStream is)
Common methods:
- readByte() read byte data
- readShort()
- readInt()
- readLong()
- readChar()
- readBoolean ()
- readFloat()
- readDouble()
- readUTF() Read string
Note: The calling sequence of methods for reading various data types must be consistent with the writing sequence.
DataOutputStream
Construction method:
DataOutputStream(OutputStream os)
Common methods:
- writeByte() write byte data
- writeShort()
- writeInt()
- writeLong()
- writeChar()
- writeBoolean()
- writeFloat()
- writeDouble()
- writeUTF() write string
End
Assignment:
Suppose there are multiple words in the file, and each word is on its own line. For
example:
Hello
World
Hello
JavaEE
…
Read out the words in the file, remove the repeated words, sort them and write them into a new file
If you need to learn other Java knowledge, poke here ultra-detailed knowledge of Java Summary