IO Stream, Four Interfaces, and Simplified Lambda Important Points

Posted by jeff21 on Sun, 19 Jan 2020 02:25:47 +0100

IO Stream

IO: Transfer data, do input and output, copy, upload and download...

Flow: A series of flowing data, flowing in a first-in, first-out fashion, in a pipe

  • By flow direction: all brain centered, program centered
  • For example: File (Data Source) - Input Stream - > Program (Destination)
  • Program - Output - > File
IO: Transfer data, do input and output, copy, upload and download...
	Different flow: pipe
 Flow classification:
	Operation unit classification:
		Byte: Input of byte output byte *****
		Characters:
	Functional points:
		Node Flow
		Functional Flow
	Follow the flow direction: in your own unit (program)
		Input stream
		output stream
	Classifications are mutually complementary
 Use of streams
	Create (parameter is File, path string)
	function
	
	Node:
		Byte stream:
			Enter FIleInputStream
			Output FIleOutputStream
		Character Stream	
			Enter FileReader
			Output FileWriter
	Functional Stream:
		Object Flow
			Enter ObjectInputStream
			Output ObjectOutputStream

Flow Classification

Byte stream:

Universal Stream, capable of transmitting any type of data

 	Byte Stream Read In Program Centered Data Source--Read In-->Program
   	InputStream Abstract parent byte input stream
  	FileInputStream file byte input stream, reading data from system files to programs
  		Inside the constructor FileInputStream(String name), a File object is built, then the constructor for the File object with the following structure is called
  			 new FileInputStream(File);
  		Method
  			Read()->Return value int, read byte data, if no data Return-1 Read data in a byte
 			read(byte[]) A byte array A byte array Read in, Returns the number of data read into the array, If not, Returns -1
 
  	Note: Strings in java indicate that paths can use \ or /, and using \ will recognize as escape characters
  	
  	
  	Byte Output Stream:
  	 OutputStream Abstract parent
  	 FileOutputStream File Byte Output Stream
  		constructor
  			FileOutputStream(String name) creates a file output stream to write to the specified name of the file.   
  				Default Overwrite
  			FileOutputStream(String name, boolean append) is written out and appended. 
  		common method
  			write(int)
  			write(byte[] b) 
			write(byte[] b, int off, int len)  
  			flush() remember to brush out before closing any output stream
  			close()
  
  	When writing out, if the file system does not exist, the system will automatically create one for you, but if the directory does not exist, the system will not create one
  	

Example:

  Data Source File----->program------>Destination Files
  //File copy:
  	1.Create Stream
  		//File Byte Input Stream
  		//File Byte Output Stream
   2.Read in and write out
   
   3.Brush out
   
   4.Close(Close after opening)
   
   
	import java.io.FileInputStream;
	import java.io.FileNotFoundException;
	import java.io.FileOutputStream;
	import java.io.IOException;
	import java.io.InputStream;
	import java.io.OutputStream;
   
   public class CopyFile03 {
	public static void main(String[] args) {
		//1. Create Stream
		InputStream is=null;
		OutputStream os=null;
		try {
			/*is=new FileInputStream("D:/test.txt");
			os=new FileOutputStream("E:/test.txt");*/
			//2. Read in and write out
			byte[] car=new byte[1024];
			int len=-1;
			while(-1!=(len=is.read(car))){
				os.write(car, 0, len);
			}
			//3. Brush out
			os.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{ //Turn off in finally is performed regardless of whether exception code is present in try
			//4. Close (turn off after turn on)
			try {
				if(os!=null){  //Prevent null pointer abnormalities
					os.close();
				}
				if(is!=null){  //Prevent null pointer abnormalities
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}
}

Character stream:

Plain text

Copy only plain text data

  • Input stream: Reader FileReader read() read (char[]) close()
  • Output stream: Writer FileWriter write () + flush () close ()

Example:

public class CharIODemo04 {
	public static void main(String[] args) throws IOException {
		//1. Select Flow
		Reader rd=new FileReader("D:/test.txt");
		Writer rt=new FileWriter("D:/haha.txt");
		//2. Read and write
		char[] car=new char[1024];
		int len=-1; //Number of reads into the array
		while((len=rd.read(car))!=-1){
			rt.write(car, 0, len);
		}
		//3. Brush out
		rt.flush();
		//4. Close
		rt.close();
		rd.close();
	}
}

Node Stream: Truly used to transfer data from data source to destination

Function Flow: Extending the functionality of Node Flow

Object Flow:

Read and Write Objects|Any Type of Data Preserve Data+Data Type

  • Use: Functional Flow (Node Flow)
  • Function Flow: Enhance the functionality and performance of Node Flow
  • ObjectInputStream object | Deserialize input stream. New method: readXxx()
  • ObjectOutputStream Object|Serialized Byte Output Stream New Method: writeXxx()
  •  Note: Polymorphism cannot occur
    
  • Serialization: The process of converting object data into a stored or transferable process that becomes serialization
  • Not all types can serialize java.io.Serializable
  • Serialization followed by deserialization
  • Read and write in the same order
  • Not all properties need to be serialized transient, property value is default
  • Static content will not be serialized
  • If the parent class implements the serialization interface, the contents of the subclass can also be serialized, and the subclass implements the serialization interface. The subclass can only serialize the contents of the subclass, but the contents of the parent class cannot be serialized.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class ObjectDemo05 {
	public static void main(String[] args) throws Exception {
		write("D:/haha.txt");
		read("D:/haha.txt");
		
	}
	
	//Serialized Output
	//Parameter name: Path to destination file
	public static void write(String name) throws FileNotFoundException, IOException{
		//1. Output stream
		ObjectOutputStream os=new ObjectOutputStream(new FileOutputStream(name));
		Person p=new Person("Zhang San",123);
		//2. Write it out
		os.writeBoolean(false);
		os.writeUTF("HAHA");
		os.writeObject(p);
		//3. Brush out
		os.flush();
		//4. Close
		os.close();
//		p.age=20;
	}
	
	//Deserialize input
	public static void read(String name) throws Exception{
		//1, Select Stream
		ObjectInputStream is = new ObjectInputStream(new FileInputStream(name));
		//2. Read in
		boolean b=is.readBoolean();
		String s=is.readUTF();
		Object o=is.readObject();
		System.out.println(b+"-->"+s+"-->"+o);
		//3. Close
		is.close();
	}
}

Four interfaces

Consumer Interface

​ Consumer
void accept(T t)

	//Consumer interface Consumer<T>  
		//void  accept(T t)
	@Test
	public void Test() {
		test("Who am I?",(str1)->System.out.println(str1));
	}
	
	public void test(String str,Consumer<String> c) {
		c.accept(str);
	}

Supply Interface

​ Supplier
​ T get()

	//Supplier<T>Supply Interface   
	//	T	  get() 
	@Test
	public void test1() {
		List li=test1(8,()->(int)(Math.random()*(100-1-1)+1));
		System.out.println(li);
	}
	
	
	public List<Integer> test1(Integer num,Supplier<Integer> s) {
		List<Integer> list=new ArrayList();
		for(int i=1;i<=num;i++) {
			list.add(s.get());
		}
		return list;
	}

Functional interface

​ Function<T,R>
​ R apply(T t)

	//Functional interface Function<T, R> 
	//R	  apply(T t)
	
	@Test
	public void test3() {
		
		System.out.println(test3("A new day is coming!",(str)->str.substring(0, 4)));
	}
	
	
	public String test3(String str,Function<String,String> s1) {
		
		
		return s1.apply(str);
	}

Deterministic interface

​ Predicate
​ boolean test(T t)

	//Predicate<T>Definition Interface  
	//	boolean test(T t)
	@Test
	public void test4() {
		System.out.println(test4("",(str)->str.equals("")));
	}
	
	public boolean test4(String str,Predicate<String> p) {
		
		return p.test(str);
	}

Method reference:

  • Simplified Lambda expression can be understood as another form of Lambda expression
  • Prerequisite: When an overridden abstract method body is implemented, it is actually implemented by calling another existing method, which can be invoked by a method reference to simplify Lambda's writing
  • Object reference:: Member method;
  • Class name: static method name;
  • Class name: Member method;
  • Requirements: The parameter list and return value of an abstract method of a functional interface must be consistent with the parameter list and return value of an internally referenced method!!!
  • Constructor reference:
  • new Person();
  • Person::new;
  • Type::: new;
public class MethodDemo02 {
	
	/*
	 * Constructor Reference
	 */
	@Test
	public void test5(){
//		Supplier<Employee> sup=()->new Employee();
		Supplier<Employee> sup=Employee::new;
		Function<Integer,Employee> fun=(i)->new Employee(i);
		Function<Integer,Employee> fun2=Employee::new;
	}
	
	/*
	 * Class name: Member method;
	 * 	If an abstract method has only one parameter, it acts as an object to call the method referenced by |
	 *  If an abstract method has two parameters, the first is the object that calls the method and the second is the parameter that calls the method
	 */
	@Test
	public void test4(){
//		BiPredicate<String, String> bi=(s1,s2)-> s1.equals(s2);
		BiPredicate<String, String> bi=String::equals;
		System.out.println(bi.test("zhangsan","zha2ngsan"));;
	}
	
	/*
	 * Class name: static method name;
	 * 	The parameter list of the abstract method is consistent with the parameter list of the referenced method and the return value is consistent
	 */
	@Test
	public void test3(){
//		Comparator<Integer> com=(d1,d2)->{return Integer.compare(d1, d2);}; 
		Comparator<Integer> com=Integer::compare; 
		System.out.println(com.compare(1, 2));;
	}
	
	/*
	 * Reference to object:Member method->Simplify Lambda structure
	 */
	@Test
	public void test2(){
		List<String> ls=Arrays.asList("aa","bb","cc","dd");
		//ls.forEach((e)->{System.out.println(e)});
		ls.forEach(System.out::println);
	}
	@Test
	public void test1(){
		PrintStream p=System.out;
//		Consumer com=(e)->{System.out.println(e);}; 
//		Consumer com=(e)->{p.println(e);}; 
		Consumer com=System.out::println; 
		com.accept("haha");
		com.accept("hehe");
		com.accept("heihei");
		com.accept("houhou");
	}
}
Published 5 original articles. Praise 5. Visits 67
Private letter follow

Topics: Java Lambda