当前位置:网站首页>Byte stream & character stream of IO stream
Byte stream & character stream of IO stream
2022-07-23 15:05:00 【Red bean ice 746】
Catalog
1.IO The characteristics of flow
2. Three classification methods of flow
2. Use byte stream to copy files
3. Use try - catch - finally Optimize resource release
4. Use try - catch - resource Further optimize resource release
2. File character input stream - Read a single character at a time
3. File character input stream - Read one character array at a time
Preface
Most applications need to realize data transmission with devices , For example, the keyboard can enter data , The display can display the running results of the program . stay Java in , Pass this through different input and output devices ( keyboard , Memory , Monitor , Network, etc ) The abstract expression of data transmission between is “ flow ”, The program allows data transmission with input and output devices through streaming .Java Medium “ flow ” All in Java.io In bag , be called IO( Input and output ) flow . IO flow : namely InputOutput Abbreviation .
One 、 understand IO flow

1.IO The characteristics of flow
IO Streams are used to handle data transfer between devices .
Java The operation of data is by means of flow .
Java The objects used to manipulate the flow are all in IO In bag .
Streams are divided into two types by operation data : Byte stream and character stream .
The flow is divided into : Input and output streams
2. Three classification methods of flow
Divide into... According to the direction of the flow : Input and output streams
It can be divided into : Byte stream and character stream
It can be divided into : Node flow and processing flow
3. The hierarchy of flows
IO Common base classes for streams :
- Abstract base stream of byte stream :InputStream and OutputStream
- Abstract base stream of character stream :Reader and Writer
Two 、 Byte stream
1. What is a byte stream
All file data is stored , It's all about Binary system Save in the form of numbers , One byte at a time , So it's the same when it's transmitted . therefore , Byte stream can transfer any file data . When operating the flow , We need to be clear at all times , No matter what kind of flow object is used , The underlying transmission is always binary data .
2. Use byte stream to copy files
The bottom layer of both audio and video files and text files is composed of bytes , So you can use byte input streams & Byte output stream completes any form of file copy ( As long as the file format before and after is guaranteed 、 There is no problem with consistent coding )
Be careful : Byte stream is not suitable for reading Chinese content output ,( stay UTF-8 In the encoding , A Chinese character is 3 Bytes ) It is easy to cause garbled code due to truncation
public static void main(String[] args) {
try {
// Create byte input stream pipeline
InputStream is = new FileInputStream("E:\\Pictures\\wx_camera_1654694320902.mp4");
// Create byte input stream pipeline
OutputStream os = new FileOutputStream("C:\\Users\\ Xiaoyin \\Desktop\\lhy.mp4");
// Define a 1024 Size byte array , Used to transfer data
byte[] buffer = new byte[1024];
int len;
while((len = is.read(buffer)) != -1){
os.write(buffer,0,len);
}
System.out.println(" Copy complete !~~~~~");
// Closed flow
os.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}3. Use try - catch - finally Optimize resource release
finall Code blocks are bound to be executed in the end , You can finally release resources here
public static void main(String[] args) {
InputStream is = null;
OutputStream os = null;
try {
// Create byte input stream pipeline
is = new FileInputStream("E:\\Pictures\\wx_camera_1654694320902.mp4");
// Create byte input stream pipeline
os = new FileOutputStream("C:\\Users\\ Xiaoyin \\Desktop\\lhy.mp4");
// Define a 1024 Size byte array , Used to transfer data
byte[] buffer = new byte[1024];
int len;
while((len = is.read(buffer)) != -1){
os.write(buffer,0,len);
}
System.out.println(" Copy complete !~~~~~");
} catch (Exception e) {
e.printStackTrace();
}finally {
// Whether the code ends normally or there is an exception, you should execute here
try {
// First judge that it is not empty , Then close the flow
if (os != null)os.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
if (is != null)is.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
4. Use try - catch - resource Further optimize resource release
public static void main(String[] args) {
try (
// Only resource objects can be placed here , After use, even if there is an exception, the resource object will be automatically called close Method to close the resource
// Create byte input stream pipeline
InputStream is = new FileInputStream("E:\\Pictures\\wx_camera_1654694320902.mp4");
// Create byte input stream pipeline
OutputStream os = new FileOutputStream("C:\\Users\\ Xiaoyin \\Desktop\\lhy.mp4");
){
// Define a 1024 Size byte array , Used to transfer data
byte[] buffer = new byte[1024];
int len;
while((len = is.read(buffer)) != -1){
os.write(buffer,0,len);
}
System.out.println(" Copy complete !~~~~~");
} catch (Exception e) {
e.printStackTrace();
}
}
3、 ... and 、 Character stream
1. What is a character stream
Because the byte stream reading Chinese may be truncated, resulting in garbled code , therefore ,java It provides the conversion flow . Character stream = Byte stream + Encoding table .
Encoding table : A table of characters and their corresponding values

2. File character input stream - Read a single character at a time

There will be no garbled code when reading Chinese characters
But the performance is slow
public static void main(String[] args) throws IOException {
Reader fr = new FileReader("D:\\IDEA\\untitled1\\ Exercise draft \\Test1\\src\\data.txt");
int code;
while ((code = fr.read()) != -1){
System.out.print((char) code);
}
}3. File character input stream - Read one character array at a time
Performance is improved relative to reading a single character
public static void main(String[] args) throws IOException {
Reader fr = new FileReader("D:\\IDEA\\untitled1\\ Exercise draft \\Test1\\src\\data.txt");
char[] buffer = new char[1024];
int len;
while ((len = fr.read(buffer)) != -1){
String rs = new String(buffer,0,len);
System.out.print(rs);
}
}4. Character output stream
public static void main(String[] args) throws IOException {
// Create a character output stream pipeline to connect with the target file
Writer fw = new FileWriter("D:\\IDEA\\untitled1\\ Exercise draft \\Test1\\src\\data.txt");
// Write a character out
fw.write(1);
fw.write('a');
fw.write(' Ha ');
// Write a string out
fw.write(" Ha ha ha ha ha ha ha ");
// Write a character array out
char[] chars = "abcdef".toCharArray();
fw.write(chars);
// Write only a part of the character array 、 character string
fw.write(chars,0,3);
fw.write(" Ha ha ha ha ha ha ha ",0,3);
// close
fw.close();
}
summary
- Byte stream is suitable for copying all file data
- Byte stream is not suitable for reading Chinese content output
- Character stream is suitable for text file operation ( read 、 Write )
边栏推荐
猜你喜欢

直播课堂系统03-model类及实体

精品国创《少年歌行》数字藏品开售,邀你共铸少年武侠江湖梦

leetcode: 17. 电话号码的字母组合

Kettle implements shared database connection and insert update component instances

Simulation of BOC modulation signal acquisition based on MATLAB

上小学之前要学会的本领指引

百度工程师眼中的云原生可观测性追踪技术

Postgresql快照优化Globalvis新体系分析(性能大幅增强)

面试官:生成订单30分钟未支付,则自动取消,该怎么实现?

MariaDB 数据库升级版本
随机推荐
[untitled] test [untitled] test
Kettle implements shared database connection and insert update component instances
C thread lock and single multithreading are simple to use
Mathematical function of MySQL function summary
uniapp实现横向点击滑动菜单
Building personal network disk based on nextcloud
MySQL 常用命令
[test platform development] XVII. The interface editing page realizes the drop-down cascade selection, and binds the module to which the interface belongs
Use of KOA framework
Openharmony South learning notes - hi3861+hc-sr04 ultrasonic testing
Kettle實現共享數據庫連接及插入更新組件實例
【机器学习基础】无监督学习(5)——生成模型
报错 | cannot read property ‘_normalized‘ of undefined
@FeignClient使用詳細教程(圖解)
[转]基于POI的功能区划分()
Full backpack!
Redis布隆过滤器
基于matlab的BOC调制解调的同步性能仿真,输出跟踪曲线以及不同超前滞后码距下的鉴别曲线
pytorch opencv pil图像预处理比较
基于simulink的双闭环矢量控制的电压型PWM整流器仿真