I / O stream in Java

keep_ coding9527 2021-05-04 14:46:55
stream java


io Flow is JavaSE The important content in the advanced chapter , Whether it's normal study , Or an interview , Or at work , We all come across io flow , This article will introduce you to Xiaobai io flow , master io Basic concepts and important contents of flow .

File Class explanation

talk about io Before flow , So let's see File class .

File Class

​ File, Well understood. , The English translation means document .Java Medium File Class declaration in java.io It's a bag , It can also be seen from this ,File Classes and io Flow is inseparable , Interconnected . Actually , To put it bluntly ,io Flow is for File Object service .File An object of class , Represents a file or a file directory ( It's a folder ).

File Class involves the creation of files or file directories 、 Delete 、 rename 、 Modification time 、 File size, etc , It does not involve writing or reading the contents of the file . If you need to read or write the contents of the file , You have to use IO Flow to complete .

Let's talk about File Class instantiation , There are usually the following constructors :

  • File(String filePath)
  • File(String parentPath,String childPath)
  • File(File parentFile,String childPath)
  • File(URI uri)

The most commonly used is the first constructor , That is, pass in a parameter , This parameter is the path of the file . When it comes to the path , Here we will introduce absolute path and relative path again .

What is the absolute path , What is the relative path ?

Absolute path : The path to the file or file directory that contains the drive letter . Take a chestnut , On my computer D On the plate pictures There's a... Under the folder beauty Folder , that "D:\pictures\beauty" It's the absolute path , Another example , Still on my computer D Under the plate , still pictures Folder , It's still in this folder beauty There's a... Under the folder my future girlfriend.jpg Pictures of the ,

my future girlfriend.jpg that "D:\pictures\beauty\my future girlfriend.jpg" Is the absolute path of the image file .

So what is the relative path ?

Relative paths : Compared with a certain path , The path indicated .

At first glance , A bit abstract , Don't worry , Take a chestnut and you'll see .

Now we all use IDEA Develop , stay IDEA in , If you develop and use JUnit Unit test method test in , The relative path is the current Module Next . If you use main() test , The relative path is the current Project Next .

image-20210503160148209.png

Pictured above , In the project There's a next one. hello.txt file , If you use the relative path to create File object ( Based on main() Create in method ) That's how it should be written

File file = new File("hello.txt");
 Copy code 

So , Relative path is relative to the path indicated under a certain path , Take this example , It's relative to project The path indicated .

Let's talk about a little detail of the write path , Path separator

windows and DOS System default use “\” To express ( You can also use it "/" Express )

UNIX and URL Use “/” To express

So we can write paths in two ways :

// The first one is : use "/" Express 
File file = new File("D:/pictures/beauty/my future girlfriend");
// The second kind : use ”\“ Express , You need two "\", The first “\” To signify an escape 
File file1 = new File("D:\\pictures\\beauty\\my future girlfriend")
 Copy code 

File Common methods of class

image-20210503164035030.png

Okay , That's it File class , Let's move on to today's play :io flow

io Stream Introduction

Classification of flows

According to different classification basis ,io The flow can be divided into 3 class

  • According to the data unit of operation, it is divided into : Byte stream Character stream

  • According to the flow of data, it can be divided into : Input stream Output stream

  • According to the role of flow, it can be divided into : Node flow Processing flow

    Icon :

image-20210503164852453.png

Flow architecture

image-20210503165040038.png

among ,4 Abstract base classes :InputStream、OutputStream、Reader、Writer, And the classes in the blue box need to be remembered and mastered .

Several stream structures are highlighted

Abstract base class Node flow ( File stream ) Buffer flow ( One kind of processing flow )
InputStream FileInputStream(read(byte[] buffer)) BufferedInputStream
OutputStream FileOutputStream(write(byte[] buffer,0,len)) BufferedOutputStream
Reader FileReader(read(char[] cbuf)) BufferedReader
Writer FileWriter(write(char[] cbuf,0,len)) BufferedWriter

The standardization process of input and output

Input process

  1. establish File Class object , Indicates the source of the data read (File The class constructor parameter is the path of the file ), The file must exist

  2. Create the corresponding input stream object , take File Class as parameters , In the constructor of the incoming stream

  3. The specific process of reading in data :

    Create the corresponding byte[] buffer or char[] cbuf

    ​ Be careful : Text file creation char[] cbuf, Non text file creation byte[] buffer

  4. Close stream resource

    explain : The exception in the program needs to use try-catch-finally Handle

Output process

  1. establish File Class object , Indicate the location of the written data .( Don't ask this file to exist )

  2. Create the corresponding output stream , take File Class as parameters , In the constructor of the incoming stream

  3. The specific process of writing data :

    ​ write(cbuf/buffer,0,len)

  4. Close stream resource

    Again , The exception in the program needs to use try-catch-finally Handle

Node flow

Node stream is also called file stream , Yes FileInputStream、FileOutputStream、FileReader、FileWriter These categories .

FileInputStream、FileOutputStream Belongs to the byte stream , Often used to deal with pictures 、 Audio 、 Video etc. (.jpg,.mp3,.mp4,.avi,.doc,.ppt And so on ) Non text files

FileReader、FileWriter Belongs to the character stream , Often used to handle text files (.txt,.java,.c,.cpp And so on )

FileReader/FileWriter Use

FileReader Use

Case study : Will be project Under the hello.txt The contents of the file are read into the program , And output to the console

/*
Will be project Under the hello.txt The contents of the file are read into the program , And output to the console
*/
public class Test {
public static void main(String[] args) {
FileReader fr = null;
try {
// Create a file object 
// because hello.txt The file is right here project Under the table of contents , So the relative path used 
File file = new File("hello.txt");
// Create character stream objects , And will file Object as a parameter 
fr = new FileReader(file);
// Create a character array to store the read data 
char[] cbuf = new char[5];
// The length of characters read 
int len;
//read(char[] cbuf): Return every read in cbuf The number of characters in the array . If the end of the file is reached , return -1
while ((len = fr.read(cbuf)) != -1){
// take char[] cbuf Converts to string output 
String s = new String(cbuf, 0, len);
System.out.print(s);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// Close stream resource , First judge whether the stream is empty 
if (fr != null) {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
 Copy code 

Be careful :

  • read(char[] cbuf) Returns the number of characters in the character array read each time , If read to the end of the file, return -1

  • The file read in must exist , Otherwise it will be reported FileNotFoundException

  • Handling of exceptions , Be sure to use try-catch-finally, stay finally Statement , To make sure that the stream resource is shut down ,

    This will not cause an exception in the previous code , The following closing flow resources will not be executed

    FileReader Read in data operation summary
    1. Instantiation File Class object

    2. Instantiation FileReader Stream object

    3. Read operation

      char[] cbuf = new char[5];
      int len;
      while((len = fr.read(cbuf)) != -1){
      // take char[] cbuf Converts to string output 
      String s = new String(cbuf, 0, len);
      System.out.print(s);
      }
       Copy code 
    4. Close stream resource

    FileWriter Use

    function : Write data from memory to a file on the hard disk .

    explain :

    • Output operation , Corresponding File Can not exist . No exception will be reported

    • File If the file in the corresponding hard disk does not exist , In the process of output , This file will be created automatically .

      File If the file in the corresponding hard disk exists : If the constructor used by the stream is :FileWriter(file,false) / FileWriter(file): An overlay of the original file If the constructor used by the stream is :FileWriter(file,true): The original file will not be overwritten , It's an addition to the original document

    Case study :

@Test
public void testFileWriter() {
FileWriter fw = null;
try {
//1. Provide File Class object , Indicate the document written to 
File file = new File("hello1.txt");
//2. Provide FileWriter The object of , For writing data 
fw = new FileWriter(file,false);
//3. Written operations 
fw.write("I have a dream!\n");
fw.write("you need to have a dream!");
} catch (IOException e) {
e.printStackTrace();
} finally {
//4. The closure of streaming resources 
if(fw != null){
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
 Copy code 

Buffer flow

Buffer stream is a kind of processing stream

The classes involved in buffer flow are :

  • BufferedInputStream( Buffer byte input stream )

  • BufferedOutputStream( Buffered byte output stream )

  • BufferedReader( Buffer character input stream )

  • BufferedWriter( Buffer character output stream )

There is already a byte stream that can solve the problem of reading and writing data in text and non text files , Why introduce buffer streams ?

What are the advantages of buffered streams over byte streams ?

Buffer flow , seeing the name of a thing one thinks of its function , It can act as a buffer . It provides a buffer inside , The default size is 8kb, Improve the reading and writing speed of the stream .

image-20210503224308515.png

therefore , Compared to node flow , We will give priority to using buffer stream to read and write files , Improve reading and writing speed .

About io There are many problems in the interview, such as file copy , This kind of problem can be dealt with by node flow , You can also use buffered stream processing

Next, we will use byte stream and buffer stream to copy text file and non text file

/*
Use io Stream copies a picture or text file
picture : Non text files , Use byte stream :FileInputStream/FileOutputStream or BufferedInputStream/BufferedOutputStream
text file : Use character stream :FileReader/FileWriter or BufferedReader/BufferedWriter
*/
public class IoCopy {
public static void main(String[] args) throws IOException {
// Create a file object ( Source and target files )
File srcFile = new File("D:\\pictures\\02.jpg"); // Source file ( route ) There must be 
File destFile = new File("D:\\pictures\\02copy.jpg"); // Target file ( route ) Can not exist 
// copyTextWithBuffer(srcFile,destFile);
copyImgWithBuffer(srcFile,destFile);
}
// Use byte stream to copy pictures 
public static void copyImg(File srcFile, File destFile){
// Create a byte stream object 
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
try {
inputStream = new FileInputStream(srcFile);
outputStream = new FileOutputStream(destFile);
// Create a byte array to store the read data 
byte[] data = new byte[5];
int len; // The length of the byte array 
//read() Returns the length of bytes read each time , Return at the end of the file -1
while ((len = inputStream.read(data)) != -1) {
outputStream.write(data, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// close resource 
if(outputStream != null){
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(inputStream != null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// Copy text files using character streams 
public static void copyText(File srcFile, File destFile) {
FileReader reader = null;
FileWriter writer = null;
try {
// Flow making 
reader = new FileReader(srcFile);
writer = new FileWriter(destFile);
// Create a character array to store data 
char[] data = new char[5];
int len; // The length of characters read 
//read() Returns the length of characters read each time , Return at the end of the file -1
while ((len = reader.read(data)) != -1) {
writer.write(data, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// Turn off the byte stream 
if(writer != null){
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(reader != null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// Buffer copy file using 
/*
The benefits of using buffered streams : Improve the read and write speed of the stream , Because there's a buffer inside , The default size is 8kb
*/
public static void copyTextWithBuffer(File srcFile, File destFile) {
FileReader reader = null;
FileWriter writer = null;
BufferedReader br = null;
BufferedWriter bw = null;
try {
// Create character stream objects 
reader = new FileReader(srcFile);
writer = new FileWriter(destFile);
// Create a buffered stream object , Passing character stream objects as parameters 
br = new BufferedReader(reader);
bw = new BufferedWriter(writer);
// The details of copying 
// Create a char[] Type array , Used to store read character data 
char[] data = new char[1024];
int len; // Length of characters read 
//read() Returns the length of characters read , When to return to -1 Read to the end of the file 
while ((len = br.read(data)) != -1) {
bw.write(data, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// Closed flow , Turn off the outer stream first ( Buffer flow ), Shut down the outer stream , Inner laminar flow ( Node flow ) It will automatically turn off , It can be omitted 
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// Use buffer streams to copy non text files such as pictures 
public static void copyImgWithBuffer(File srcFile,File destFile){
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
// Create buffer stream and byte stream objects , And pass the parameters 
bis = new BufferedInputStream(new FileInputStream(srcFile));
bos = new BufferedOutputStream(new FileOutputStream(destFile));
// Copy 
byte[] data = new byte[1024];
int len;
while ((len = bis.read(data)) != -1){
bos.write(data,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// Closed flow 
try{
if(bos != null){
bos.close();
}
}catch (Exception e){
e.printStackTrace();
}
try{
if(bis != null){
bis.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
}
 Copy code 

That's all JavaSE in io The basic content of flow Introduction , It's also io The core of the stream . Because the editor's level is limited , Inevitably, there are omissions and deficiencies , I hope the majority of netizens point out that , thank !

版权声明
本文为[keep_ coding9527]所创,转载请带上原文链接,感谢
https://javamana.com/2021/05/20210504144300952z.html

  1. ASP调用SDK微信分享好友、朋友圈
  2. ASP calls SDK wechat to share friends and circle of friends
  3. SpringCloud(六)Bus消息总线
  4. 详解JavaScript中的正则表达式
  5. Springcloud (6) bus message bus
  6. Explain regular expressions in JavaScript
  7. Java 响应式关系数据库连接了解一下
  8. Java14它真的来了, 真是尾气都吃不到了
  9. 视频:使用Docker搭建RabbitMQ环境
  10. Java responsive relational database connection
  11. Java14 it's really coming. I can't eat the exhaust
  12. Video: building rabbitmq environment with docker
  13. SpringCloud(六)Bus消息总线
  14. 详解JavaScript中的正则表达式
  15. Springcloud (6) bus message bus
  16. Explain regular expressions in JavaScript
  17. Docker实战:用docker-compose搭建Laravel开发环境
  18. Docker: building laravel development environment with docker compose
  19. 求助,JAVA如何获取系统当前所有进程
  20. 有人用过JMeter或用HttpUnit写过测试吗????
  21. Help, Java how to get all the current processes of the system
  22. Has anyone ever used JMeter or written tests in httpUnit????
  23. Living in a mountain village in late spring
  24. Partridge day, spring of HKUST
  25. JavaScript异步编程4——Promise错误处理
  26. 海康摄像SDK开发笔记(一):海康威视网络摄像头SDK介绍与模块功能
  27. JavaScript asynchronous programming 4 -- promise error handling
  28. Haikang video SDK development notes (1): introduction and module functions of Hikvision webcam SDK
  29. JOP:用于FPGA的嵌入式实时系统中的Java优化处理器内核
  30. Spring Boot源码:使用MongoDB MongoTemplate公开REST在几分钟内实现CRUD功能
  31. Spring Boot应用程序事件教程 - reflectoring
  32. 带有Resilience4j断路器的Spring云网关 - rome
  33. 经验分享:Apache Kafka的缺点与陷阱 - Emil Koutanov
  34. 通过Spring Boot Webflux实现Reactor Kafka
  35. 从Java 8升级到Java 11应该注意的问题
  36. Jop: Java optimized processor core for FPGA embedded real time system
  37. Spring boot source code: use mongodb mongotemplate to open rest to realize crud function in a few minutes
  38. Spring boot application event tutorial - reflecting
  39. Spring cloud gateway with resilience4j circuit breaker - ROM
  40. Experience sharing: shortcomings and pitfalls of Apache Kafka - Emil koutanov
  41. Realization of reactor Kafka through spring boot Webflux
  42. RPC框架设计----Socket与I/0模型
  43. Problems in upgrading from Java 8 to Java 11
  44. RPC framework design -- socket and I / 0 model
  45. RPC框架设计----I/0模型
  46. RPC framework design: I / 0 model
  47. RPC框架设计----NIO编程缓冲区Buffer
  48. RPC框架设计----NIO编程缓冲区Buffer
  49. RPC framework design -- NiO programming buffer
  50. RPC framework design -- NiO programming buffer
  51. Java多线程基础
  52. Java multithreading Foundation
  53. 码农飞升记-00-Java发展历程
  54. Development history of coder-00-java
  55. 码农飞升记-00-Java发展历程
  56. Development history of coder-00-java
  57. Spring and Autumn Moon
  58. Node.js与Spring Boot比较? - Ryan Gleason
  59. Spring WebFlux的明显陷阱 - ŁukaszKyć
  60. Spring创始人Rod大叔对YAML的真实想法