<> one ,IO Flow overview

Classification of flow

* 1. Operational data unit : Byte stream , Character stream
* 2. Data flow : Input stream , Output stream
* 3. The role of flow : Node flow , Processing flow

<> two , Node flow ( File stream )

<>1. FileReader

Explanation point :

take day09 Next hello.txt The contents of the file are read into the program , And output to the console

* read() Understanding of : Returns a character read in . If the end of the file is reached , return -1
* Exception handling : In order to ensure that the stream resource can be closed . Need to use try-catch-finally handle
* The read in file must exist , Otherwise it will be reported FileNotFoundException. @Test public void testFileReader() {
FileReader fr= null; try { //1. File Class instantiation File file = new File("hello.txt"); //
Relative to the current module lower //2. FileReader Instantiation of stream fr = new FileReader(file); //3. Read in operation
read() Returns a character read in int data = fr.read(); // while (data != -1) { //
System.out.print((char)data); // data = fr.read(); // } while ((data = fr.read()
) != -1) { System.out.print((char) data); } } catch (IOException e) { e.
printStackTrace(); } finally { if (fr != null) { // The judgment here is that if fr = new
FileReader(file); After an exception occurs ,fr by null, But it will be implemented finally Content of , here fr.close(); Will report null pointer exception try { fr.
close(); } catch (IOException e) { e.printStackTrace(); } } } } @Test public
void testFileReader1() { FileReader fr = null; try { File file = new File(
"hello.txt"); fr = new FileReader(file); char[] ch = new char[5]; int len; //
Number of characters read in each time read(char[] ch) // How many characters are read at a time while ((len = fr.read(ch)) != -1) {
// Mode one : // Wrong writing // for (int i = 0; i < ch.length; i++) { //
System.out.print(ch[i]); // } // Correct writing , Only read in len( Number of characters read ) // for (int i = 0; i
< len; i++) { // System.out.print(ch[i]); // } // Mode 2 : // Wrong writing // String str =
new String(ch); // System.out.print(str); // Correct writing , Only read in len( Number of characters read ) String
str= new String(ch, 0, len); System.out.print(str); } } catch (IOException e) {
e.printStackTrace(); } finally { if (fr != null) { try { fr.close(); } catch (
IOException e) { e.printStackTrace(); } } } }
<>2. FileWriter

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

explain :

* Output operation , Corresponding File It can't 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 is 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): Covering the original file
If the constructor used by the stream is :FileWriter(file,true): The original file will not be overwritten , Instead, the content is added to the original document @Test public void
testFileWriter() { FileWriter fw = null; try { //1. provide File Class , Indicates the file to write to File file
= new File("hello1.txt"); //2. provide FileWriter Object of , For data writing fw = new FileWriter(file,
false); //3. The operation of writing fw.write("I have a dream!\n"); fw.write("you need to have a
dream!"); } catch (IOException e) { e.printStackTrace(); } finally { //4. Closing of stream resources
if(fw != null){ try { fw.close(); } catch (IOException e) { e.printStackTrace();
} } } } 1.3 Copy of text file : @Test public void testFileReaderFileWriter() { FileReader
fr= null; FileWriter fw = null; try { //1. establish File Class , Indicates the documents read in and written out File srcFile =
new File("hello.txt"); File destFile = new File("hello2.txt");
// You cannot use character stream to process byte data such as pictures // File srcFile = new File(" Love and friendship .jpg"); // File destFile =
new File(" Love and friendship 1.jpg"); //2. Create objects for input and output streams fr = new FileReader(srcFile); fw = new
FileWriter(destFile); //3. Read in and write out of data char[] cbuf = new char[5]; int len;
// Record each read to cbuf The number of characters in the array while((len = fr.read(cbuf)) != -1){
// Write every time len Characters ( Exactly the number of files read in ) fw.write(cbuf,0,len); } } catch (IOException e) { e.
printStackTrace(); } finally { //4. Turn off stream resources // Mode one : // try { // if(fw != null) //
fw.close(); // } catch (IOException e) { // e.printStackTrace(); // }finally{
// try { // if(fr != null) // fr.close(); // } catch (IOException e) { //
e.printStackTrace(); // } // } // Mode 2 : try { if(fw != null) fw.close(); } catch (
IOException e) { e.printStackTrace(); } try { if(fr != null) fr.close(); } catch
(IOException e) { e.printStackTrace(); } } } 2.FileInputStream /
FileOutputStream Use of :* 1. For text files (.txt,.java,.c,.cpp), Using character stream processing * 2. For non text files (.jpg,.
mp3,.mp4,.avi,.doc,.ppt,...), Using byte stream processing /* Realize the copy operation of the picture */ @Test public void
testFileInputOutputStream() { FileInputStream fis = null; FileOutputStream fos =
null; try { //1. Making documents File srcFile = new File(" Love and friendship .jpg"); File destFile = new
File(" Love and friendship 2.jpg"); //2. Stream making fis = new FileInputStream(srcFile); fos = new
FileOutputStream(destFile); //3. The process of copying byte[] buffer = new byte[5]; int len;
while((len = fis.read(buffer)) != -1){ fos.write(buffer,0,len); } } catch (
IOException e) { e.printStackTrace(); } finally { if(fos != null){ //4. Close the flow try {
fos.close(); } catch (IOException e) { e.printStackTrace(); } } if(fis != null)
{ try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } }
<> three , Buffer flow
1. Classes involved in buffer flow : * BufferedInputStream * BufferedOutputStream * BufferedReader *
BufferedWriter2. effect : effect : Provides the reading of the stream , Write speed Reasons for improving reading and writing speed : A buffer is provided internally . By default, it is 8kb 3. Typical code 3.1
use BufferedInputStream and BufferedOutputStream: Processing non text files // How to copy files public void
copyFileWithBuffered(String srcPath,String destPath){ BufferedInputStream bis =
null; BufferedOutputStream bos = null; try { //1. Making documents File srcFile = new File(
srcPath); File destFile = new File(destPath); //2. Stream making //2.1 Create node flow FileInputStream
fis= new FileInputStream((srcFile)); FileOutputStream fos = new FileOutputStream
(destFile); //2.2 Create buffer flow bis = new BufferedInputStream(fis); bos = new
BufferedOutputStream(fos); //3. Details of copying : read , write in byte[] buffer = new byte[1024]; int
len; while((len = bis.read(buffer)) != -1){ bos.write(buffer,0,len); } } catch (
IOException e) { e.printStackTrace(); } finally { //4. Resource shutdown // requirement : Turn off the outer flow first , Then close the inner flow
if(bos != null){ try { bos.close(); } catch (IOException e) { e.printStackTrace(
); } } if(bis != null){ try { bis.close(); } catch (IOException e) { e.
printStackTrace(); } } // explain : While closing the outer layer flow , The inner layer flow is also automatically closed . On the closure of inner laminar flow , We can omit it . //
fos.close(); // fis.close(); } } 3.2 use BufferedReader and BufferedWriter: Processing text files
@Test public void testBufferedReaderBufferedWriter(){ BufferedReader br = null;
BufferedWriter bw= null; try { // Create files and corresponding streams br = new BufferedReader(new
FileReader(new File("dbcp.txt"))); bw = new BufferedWriter(new FileWriter(new
File("dbcp1.txt"))); // Read write operation // Mode one : use char[] array // char[] cbuf = new char[1024];
// int len; // while((len = br.read(cbuf)) != -1){ // bw.write(cbuf,0,len); //
// bw.flush(); // } // Mode 2 : use String String data; while((data = br.readLine()) !=
null){ // Method 1 : // bw.write(data + "\n");//data Line breaks are not included in // Method 2 : bw.write(data);
//data Line breaks are not included in bw.newLine();// Provides line feed operations } } catch (IOException e) { e.
printStackTrace(); } finally { // close resource if(bw != null){ try { bw.close(); } catch
(IOException e) { e.printStackTrace(); } } if(br != null){ try { br.close(); }
catch (IOException e) { e.printStackTrace(); } } } }
<> four , Conversion flow

1. The classes involved in the transformation flow : Belongs to character stream
InputStreamReader: Converts a byte input stream to a character input stream
decode : byte , Byte array —> Character array , character string

OutputStreamWriter: Converts the output stream of one character to the output stream of bytes
code : Character array , character string —> byte , Byte array

explain : Encoding determines the way of decoding

2. effect : Provides conversion between byte stream and character stream

3. Diagram :

4. Typical implementation : @Test public void test1() throws IOException { FileInputStream fis =
new FileInputStream("dbcp.txt"); // InputStreamReader isr = new
InputStreamReader(fis);// Use the system default character set // parameter 2 Indicates the character set , Which character set to use , It depends on the file dbcp.txt The character set to use when saving
InputStreamReader isr= new InputStreamReader(fis,"UTF-8");// Use the system default character set char[]
cbuf= new char[20]; int len; while((len = isr.read(cbuf)) != -1){ String str =
new String(cbuf,0,len); System.out.print(str); } isr.close(); } /*
If the exception is handled at this time , It should still be used try-catch-finally Comprehensive use InputStreamReader and OutputStreamWriter */
@Test public void test2() throws Exception { //1. Making documents , Stream making File file1 = new File(
"dbcp.txt"); File file2 = new File("dbcp_gbk.txt"); FileInputStream fis = new
FileInputStream(file1); FileOutputStream fos = new FileOutputStream(file2);
InputStreamReader isr= new InputStreamReader(fis,"utf-8"); OutputStreamWriter
osw= new OutputStreamWriter(fos,"gbk"); //2. Reading and writing process char[] cbuf = new char[20]; int
len; while((len = isr.read(cbuf)) != -1){ osw.write(cbuf,0,len); } //3. close resource isr
.close(); osw.close(); }

5. explain :
// How to code files ( such as :GBK), Determines the character set to use for parsing ( It can only be GBK).

<> five , Standard I / O stream , Print stream , data stream ( understand )
1. Standard input and output streams : System.in: Standard input stream , Input from keyboard by default System.out: Standard output stream , Output from console by default Default input and output behavior :
System Class setIn(InputStream is) / setOut(PrintStream ps) Method to reassign the input and output streams . 2. Print stream :
PrintStream and PrintWriter explain : Provides a series of overloaded print() and println() method , Output for multiple data types System.
out What is returned is PrintStream Examples of 3. data stream : DataInputStream and DataOutputStream effect :
A variable or string used to read or write basic data types Sample code :/* practice : String in memory , Write the variables of basic data type to the file .
be careful : If you handle an exception , It should still be used try-catch-finally. */ @Test public void test3() throws
IOException{ //1. DataOutputStream dos = new DataOutputStream(new
FileOutputStream("data.txt")); //2. dos.writeUTF(" Liu Jianchen "); dos.flush();
// Refresh operation , Write the data in memory to a file dos.writeInt(23); dos.flush(); dos.writeBoolean(true); dos.
flush(); //3. dos.close(); } /* Read the basic data type variables and strings stored in the file into memory , Save in variable .
Pay attention : Read different types of data in the same order as when writing to the file , The stored data is in the same order ! */ @Test public void test4() throws
IOException{ //1. DataInputStream dis = new DataInputStream(new FileInputStream(
"data.txt")); //2. String name = dis.readUTF(); int age = dis.readInt(); boolean
isMale= dis.readBoolean(); System.out.println("name = " + name); System.out.
println("age = " + age); System.out.println("isMale = " + isMale); //3. dis.
close(); }
<> six , Object flow

* Object flow :
ObjectInputStream and ObjectOutputStream
* effect :
ObjectOutputStream: Objects in memory —> Files in storage , It's transmitted through the network : Serialization process
ObjectInputStream: Files in storage , Received over the network —> Objects in memory : Deserialization process
* Serialization mechanism of object :
The object serialization mechanism allows the Java Object into a platform independent binary stream , This allows the binary stream to be persisted on disk
upper , Or transfer the binary stream to another network node through the network .// When other programs get this binary stream , You can get back to the original Java object 4. Implementation of serialization code : @Test
public void testObjectOutputStream(){ ObjectOutputStream oos = null; try { //1.
oos= new ObjectOutputStream(new FileOutputStream("object.dat")); //2. oos.
writeObject(new String(" I Love Beijing Tiananmen ")); oos.flush();// Refresh operation oos.writeObject(new
Person(" Wang Ming ",23)); oos.flush(); oos.writeObject(new Person(" placed under house arrest ",23,1001,new
Account(5000))); oos.flush(); } catch (IOException e) { e.printStackTrace(); }
finally { if(oos != null){ //3. try { oos.close(); } catch (IOException e) { e.
printStackTrace(); } } } } 5. Implementation of deserialization code : @Test public void testObjectInputStream()
{ ObjectInputStream ois = null; try { ois = new ObjectInputStream(new
FileInputStream("object.dat")); Object obj = ois.readObject(); String str = (
String) obj; Person p = (Person) ois.readObject(); Person p1 = (Person) ois.
readObject(); System.out.println(str); System.out.println(p); System.out.println
(p1); } catch (IOException e) { e.printStackTrace(); } catch (
ClassNotFoundException e) { e.printStackTrace(); } finally { if(ois != null){
try { ois.close(); } catch (IOException e) { e.printStackTrace(); } } } }
<>6. The class of the object that implements serialization needs to meet the :

* 1. Need to implement interface :Serializable
*
2. The current class provides a global constant :serialVersionUID

*
3. Except for the present Person Class needs to be implemented Serializable Outside the interface , It must also guarantee its internal attributes

*
It must also be serializable .( By default , The basic data type is serializable )

*
supplement :ObjectOutputStream and ObjectInputStream Cannot serialize static and transient Modified member variable

transient To modify a member that is not serialized !

Technology