The way to learn java IO stream and XML

Xiaobai learning java 2021-05-04 14:54:42
way learn java io stream


In fact, before I study database , Data visualization , It used to be io+ Regular expressions + String processing and so on , Dare to believe ?io Operation is very important !!!

1、IO summary

IO:Input( Input : Read files from disk into memory ) | Output( Write data in memory to disk );

file : The organizational unit of data on disk ( A bunch of bytes of data )

flow (Stream): Change static byte data in disk into byte data in flow ;( A sequence of bytes forms a stream )

All interfaces and classes for reading and writing files are placed in :java.io In bag ;

2、File class

Detect files | Folder information , Further to the document | Folder operation ;

File : Get information about the file | establish | Delete | rename | Move , Wait for the operation

To directory : Provide deletion | Create a directory and get all the files and folders under the directory

Get all the resources in the specified directory ( Files or folders -- Recursive get )

public static void getFileAndDirectory(File path) {
try{
File[] files = path.listFiles();
for(File f :files) {
if(f.isDirectory()) {
// Print the catalog Information ;
System.out.println(f.getPath());
// And recursively call ;
getFileAndDirectory(f);
}else {
System.out.println(f.getPath());
}
}
}catch(Exception e){}
}
 Copy code 
3、IO flow

A、 Byte stream 【 important 】

Read and write to the file, the lowest level of , Byte stream can be used for any format To operate on ;

public abstract class InputStream : The byte stream parent of the read operation ( abstract class )
public class FileInputStream extends InputStream ;
InputStream
-- FileInputStream
 Copy code 
 One byte can be read from the stream at a time (read Method ), If you return -1, Indicates that you have reached the end of the stream ( After reading )
 Copy code 
 Batch read byte stream data :read(byte[] data) | read(byte[] data,int startindex,int len)
 Copy code 

Byte write stream

public abstract class OutputStream
public class FileOutputStream extends OutputStream
 Copy code 
write(byte[] datas)
write(int data)
write(byte[] datas,int startindex,int len)
 Copy code 

How to copy a file

 // Copy file ;
public static void copy(String src,String dest) {
InputStream in = null;
OutputStream out = null;
try {
//1. Create a read | Write stream objects
in = new FileInputStream(src);
out = new FileOutputStream(dest);
// How much at a time ? -- 4k |8k;
byte[] buffer =new byte[1024*4];
int len = -1;
while((len=in.read(buffer))!=-1) { //read The return value of the method is the length of the actual read stream ;
// take buffer The data in is written to the output stream ;
out.write(buffer,0,len);
}
}catch (IOException e) {
e.printStackTrace();
}finally {
// Be sure to turn off the output stream first , Turn off the input stream ;
if(out!=null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(in!=null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
 Copy code 

B、 Character stream [ important ]

Read and write to disk text file , It can be realized with byte stream , But it's not very convenient ;SUN A stream of design majors ( Character stream ), Read and write files in text format , Relative byte stream , It's more convenient ; To provide efficiency , Use it again SUN Designed buffer stream

Read through character stream Text format file ( Can't read image file through character stream , Sound files , Video files, etc )

public abstract class Reader
public class FileReader extends InputStreamReader extends Reader
read()
read(char[] data) | read(char[] data,int index,int len)
 Copy code 
public abstract class Writer
public class FileWriter extends OutputStreamWriter extends Writer
write(int c) | writer(String str)
writer(char[] chars) | writer(char[] chars,int index,int len)
 Copy code 

C、 Character buffer stream [ important ]

Character buffer stream can only buffer character stream , The character buffer stream has 2 individual :BufferedReader , BufferedWriter

public class BufferedReader extends Reader
public class BufferedWriter extends Writer
 Copy code 

D、 Standard input stream and standard standby output stream [ understand ]

System.in : Get keyboard data ;
System.out: Output --- Monitor | Console
 Copy code 
public final class System {
public final static InputStream in = null; Keyboard data
public final static PrintStream out = null;
}
 Copy code 

E、 Converted flow

Stream bytes become Character stream ( A one-way )

public class InputStreamReader extends Reader
public class OutputStreamWriter extends Writer
 Copy code 

F、 Object flow

Object flow : How to persist an object ( The role of object flow )

serialize : Turn objects into streams , Used for storage or network transmission ;

Deserialization : Turn the data in the stream into objects

** notes :** Objects created by a class should be serializable , This class must be implemented Serializable Interface ( It's a sign , There's no design )

public class ObjectOutputStream extends OutputStream
public class ObjectInputStream extends InputStream
 Copy code 
transient : If an attribute does not need to be held , Just add this logo
private transient String nick;
 Copy code 

G、 Data flow

Data flow : Persisting data and strings of basic data types ;

public class DataInputStream extends FilterInputStream extends InputStream
public class DataOutputStream extends FilterOutoputStream extends OutputStream
 Copy code 
4、XML[ important ]

XML:Extensible Markup Language ( Extensible markup language ),xml It's a plain text file , Relative to text files , The content of a document is usually wrapped in labels ( Easy to parse ); XML In the project, it is mainly used to store configuration information ( Every project has a configuration file (xml file ))

XML Document function : Store data ( Project configuration information )

XML Documentation specifications :

  • The first 1 Behavior document declaration ( The writing is fixed , You don't need to write it , Development tools automatically generate )
  • xml There is only one root element ( node )
  • label ( Elements ) It needs to be wrapped in a pair of angle brackets ; Labels usually appear in pairs , The start tag is only different from the end tag “/"
  • xml case-sensitive ( It's usually in lowercase )
  • Elements can have attributes , Multiple attributes need to be separated by spaces , Property values need to be enclosed in double quotation marks ( Attributes need to be placed in the start tag )

XML The document is general 3 Three ways of writing

<?xml version="1.0" encoding="UTF-8"?>
<users>
<user>
<name> Zhang Er </name>
<job>C The programmer </job>
<nick> Senior programmer </nick>
<email>zhanger@qq.com</email>
</user>
</users>
 Copy code 
<?xml version="1.0" encoding="UTF-8"?>
<users>
<user name=" Zhang Yi " job=" rookie " nick=" Junior programmer " email="zhang@qq.com" />
<user name=" Zhang Er " job=" veteran " nick=" Senior programmer " email="zhanger@qq.com"/>
</users>
 Copy code 
<?xml version="1.0" encoding="UTF-8"?>
<users>
<user id="1">
<name> Zhang Yi </name>
<job> The programmer </job>
<nick> senior </nick>
<email>zhang@qq.com</email>
</user>
</users>
 Copy code 

analysis XML : stay JDK in SUN A set of classes and interfaces are designed , Used to resolve XML file ( In the book );SUN Analysis of design XML It's not very convenient to use , So in practice , General third party parsing components (jar) ---- DOM4J

DOM4J Core components (org.dom4j | org.dom4j.io)
SAXReader : Reader
Document:XML Document class
Element : XML Elements
XMLWriter : Write data class
OutputFormat: Format class
DocumentHelper:Document Helper
 Copy code 

Default , Without adding any constraints XML The documentation is arbitrary ( Any tag name , The label design included in the label is also random ), The biggest drawback of this : It's not easy to parse ( You can't write a program to parse an arbitrary structure XML file ), Disordered document structure , So we need a structure determined XML file ----- To current XML Design document structure **( constraint )** ------ at present , The design of document structure can have 2 Ways of planting

DTD:(Document Type Definition) It's a set of defining grammar rules ; DTD It can be written inside the document ( Inside DTD), It can also be written outside the document ( external DTD), To the outside DTD, Just bring it in the current document

The grammar introduced :

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE users SYSTEM "txl.dtd" >
SYSTEM: Express private ownership DTD , At present DTD Only for this project ( One of them XML file )
 Copy code 
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
PUBLIC : Public ( All projects can introduce this constraint ), Open DTD Generally used in the framework
 Copy code 

understand DTD The grammar of ( How to write a DTD)

<!ELEMENT users (user*)> :ELEMENT Element settings ( The root element is users, The root element child element name is user, Number 0 One or more )
<!ELEMENT user(name,job?,email*) :user Elements have 3 Sub elements ,name The element must have ,job 0 A or 1 individual ,email0 One or more
<!ELEMENT name (#PCDATA)> name Type of element #PCDATA: Indicates the character type
<!ELEMENT job (#PCDATA)>
<!ELEMENT email (#PCDATA)>
 Copy code 

XML Schema :

XML framework , relative DTD,Schema The design provided is more complex , More comprehensive . Schema The constraint itself is also a xml file (xsd)

<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://localhost/txl"
xmlns:tns="http://www.example.org/txl" elementFormDefault="qualified">
</schema>
xmlns="http://www.w3.org/2001/XMLSchema" : Set the name space from which the element type of this file comes ( Value cannot be modified )
targetNamespace="http://www.example.org/txl" : To introduce this schema Of xml The development of file service
elementFormDefault="qualified" : Set whether the element defaults to a namespace
 Copy code 
element : Define the element
complexType: Define composite elements | Complex elements
sequence: The elements appear in sequence
minOccurs="0" : It's the smallest one
maxOccurs="unbounded" : The biggest online
......
 Copy code 
<users
xmlns="http://localhost/txl"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://localhost/txl txl.xsd ">
</users>
xmlns="http://localhost/txl" Value and targetNamespace The value is consistent.
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" : tell xml Parser , Ben xml Use one xmlschema example
xsi:schemaLocation="http://localhost/txl txl.xsd " :schema Address
 Copy code 
5、 Layered development [ important ]

Classes in a normal project don't go into a package , The main management is not convenient , So in the actual project , Classes are always based on functional Subcontract Management --- Layered design idea ( branch 3 layer )

The presentation layer : Display data ( forms | Webpage | Console )

Business logic layer : Business logic judgment ( Sign in ) ; If the business layer has no business processing , The business layer just plays the role of data transmission ( Baton )

The data layer : Interacting with files or databases ( Complete data persistence or read data from files and databases )

stay JAVA In the project design of , Layering is reflected through subcontracting ;

版权声明
本文为[Xiaobai learning java]所创,转载请带上原文链接,感谢
https://javamana.com/2021/05/20210504144301098u.html

  1. Help, Java how to get all the current processes of the system
  2. Has anyone ever used JMeter or written tests in httpUnit????
  3. Living in a mountain village in late spring
  4. Partridge day, spring of HKUST
  5. JavaScript异步编程4——Promise错误处理
  6. 海康摄像SDK开发笔记(一):海康威视网络摄像头SDK介绍与模块功能
  7. JavaScript asynchronous programming 4 -- promise error handling
  8. Haikang video SDK development notes (1): introduction and module functions of Hikvision webcam SDK
  9. JOP:用于FPGA的嵌入式实时系统中的Java优化处理器内核
  10. Spring Boot源码:使用MongoDB MongoTemplate公开REST在几分钟内实现CRUD功能
  11. Spring Boot应用程序事件教程 - reflectoring
  12. 带有Resilience4j断路器的Spring云网关 - rome
  13. 经验分享:Apache Kafka的缺点与陷阱 - Emil Koutanov
  14. 通过Spring Boot Webflux实现Reactor Kafka
  15. 从Java 8升级到Java 11应该注意的问题
  16. Jop: Java optimized processor core for FPGA embedded real time system
  17. Spring boot source code: use mongodb mongotemplate to open rest to realize crud function in a few minutes
  18. Spring boot application event tutorial - reflecting
  19. Spring cloud gateway with resilience4j circuit breaker - ROM
  20. Experience sharing: shortcomings and pitfalls of Apache Kafka - Emil koutanov
  21. Realization of reactor Kafka through spring boot Webflux
  22. RPC框架设计----Socket与I/0模型
  23. Problems in upgrading from Java 8 to Java 11
  24. RPC framework design -- socket and I / 0 model
  25. RPC框架设计----I/0模型
  26. RPC framework design: I / 0 model
  27. RPC框架设计----NIO编程缓冲区Buffer
  28. RPC框架设计----NIO编程缓冲区Buffer
  29. RPC framework design -- NiO programming buffer
  30. RPC framework design -- NiO programming buffer
  31. Java多线程基础
  32. Java multithreading Foundation
  33. 码农飞升记-00-Java发展历程
  34. Development history of coder-00-java
  35. 码农飞升记-00-Java发展历程
  36. Development history of coder-00-java
  37. Spring and Autumn Moon
  38. Node.js与Spring Boot比较? - Ryan Gleason
  39. Spring WebFlux的明显陷阱 - ŁukaszKyć
  40. Spring创始人Rod大叔对YAML的真实想法
  41. Compare node.js with spring boot- Ryan Gleason
  42. Obvious pitfalls of spring Webflux- Ł ukaszKy ć
  43. Spring founder uncle rod's real thoughts on yaml
  44. 码农飞升记-02-OracleJDK是什么?OracleJDK的版本怎么选择?
  45. What is manong feisheng-02-oracle JDK? How to choose the version of Oracle JDK?
  46. Spring tide surging Xinanjiang
  47. Linux内核软中断
  48. Linux kernel soft interrupt
  49. Linux内核软中断
  50. Linux kernel soft interrupt
  51. Java multithreading Foundation
  52. The construction of Maven private library nexus
  53. I / O stream in Java
  54. JDK 16:Java 16的新功能 - InfoWorld
  55. 在Java中本地进行线程间数据传输的三种方式和源码展示
  56. jdon导致cpu 99%最后tomcat死掉---banq给予回复
  57. 用领域事件模拟AOP注入
  58. JDK 16: new function of Java 16 - InfoWorld
  59. Cartoon: from JVM lock to redis distributed lock
  60. Spring 3.1 终于加入了Cache支持