Java learning notes (5)

Fu Yao laughs at cangming 2020-11-09 00:28:29
java learning notes


One 、 Streaming of sets

stay JDK8 in the future , Provides streaming operations on collections , Elements of a set can be directed to “ Running water ” equally , Convenient in turn , Traverse , Sort, etc , It is “ irreversible ”( After accessing the following element, you cannot return the previous element again ) , Depending on how streams are handled , Can be divided into Serial and parallel streams , A serial stream means that there can be only one streaming operation at a time , Parallel streams can have multiple streaming operations .

​ The results returned by the stream include intermediate operations and Final operation

Intermediate operation : Its return value is still Stream object , for example Sort 、 Filter 、 duplicate removal

Final operation : The return value is a specific result type , for example Traverse , Taking the maximum , Minimum or return a new set

Common methods :

​ stream() : Stream a set

​ filter(): Filter by condition , It uses lambda expression

​ sort(): Sort set elements

​ distinct: Filter repeating elements

​ reduce() : Add or splice all elements of a collection

​ map(); A new set of mappings Change the output to the set element

​ collect(): Return to a new collection

​ max() min(): Returns the maximum or minimum value of a set

​ get (): Get the result of set calculation

 public static void main(String[] args) {
List<Integer> list = new ArrayList();
for(int i = 0 ;i<7;i++){
// 1、 Filter filter() Filter out even numbers param ->param%2==1 )
.forEach(System.out::println); // Traversing elements 
// 2、 Sort sort() Descending,o2)->o2-o1).forEach(System.out::println);
// 3 map() A new set of mappings , If it's odd Output odd , Otherwise even numbers
param -> param%2==1?" This element is odd ":" This is an even number "
System.out.println(" Remove heavy elements ");
// 4 distinct() Remove duplicate elements;
// 5 reduce() Will set all the elements of Add up ( Or splicing )
int sum =,o2)->o1+o2).get();
System.out.println(" The sum of the :"+sum);
// 6 collect Returns a new collection 
List<Integer> list2=>param%2==1).collect(Collectors.toList());
System.out.println(" Traverse the new set ");;
// 7、 Maximum and minimum 
int max =,o2)->o1-o2 ).get();
System.out.println(" Maximum :"+max);
int min =,o2)->o1-o2 ).get();
System.out.println(" minimum value :"+min);


One 、Java Of I/O

1、 What is? I/O?

​ In the life , You need to U Files on disk , Copy to a computer ( Or copy computer files to other devices ), Files are sent to another device by data stream , A copy of a file is an input (Input) And the output (Output) The process of

Java Provides the corresponding API Support the input and output of files ,*

2、 What is flow ?

In life There is also the concept of flow , for example The running water in the pipe , From the entrance of the pipe to the outlet of the pipe , A drop of water can flow from the inlet to the outlet , Can be “ water ” Compared to the “ Byte data or character data ”, Data can also flow from one end to the other .

Input (Input): Java in , With “ Applications ( Memory )” Centered , Put the disk file ( Device end ) The process of reaching memory be called Input

Output (Output): With “ Applications ( Memory )” Centered , Transfer data from memory to disk file ( Device end ) The process is called Output

According to the file operation mode, you can change IO Divided into three categories

1、 According to the direction of reading and writing : Input stream (InputStream) And the output stream (OutputStream)

2、 According to the data type : Byte stream (Byte) And character streams (Char)

3、 According to the reading and writing efficiency : Stream and single packaging (buffered Wait for the buffer stream )

On the classification of flows Java Provide 4 Top level abstract classes , Distributions build their subclasses

Input stream Output stream
Byte stream InputStream( Byte input stream ) OutputStream( Byte output stream )
Character stream Reader( Character input stream ) Writer( The output stream of characters )

The common stream

  • 1、 File byte input stream and file byte output stream : FileInputStream and FileOutputStream

  • 2、 File character input stream and file character output stream : FileReader and FileWriter

  • 3、 Cache byte input stream and Cache byte output stream BufferedInputStream and BufferedOutputStream

  • 4、 Cache character input stream and buffered character output stream BufferedReader and BuffereWriter

  • 5、 Data input stream and data output stream : DataInputStream and DataOutputStream

  • 6、 Byte array input stream and Byte array output stream : ByteArrayInputStream and ByteArrayOutputStream

  • 7、 Character array input stream and Character array output stream : CharArrayReader and CharArrayWriter

  • 8、 Converted flow : ( Bytes flow into a stream of characters ) InputStreamReader and OutputStreamWriter

  • 9、 Object flow ( Serialization flow ): ObjectInputStream and ObjectOutputStream

  • 10、 Random access stream ( This stream can read , Can also write ):RandomAccessFIle

Byte stream

​ Definition : The input and output of the file are as follows “ byte ” In units of , Stream processing

FileInputStream and FileOutputStream

Read in : Read the data in the file into memory

Common methods :

​ int read() : A byte read , Return byte Of asci code , Chinese characters can be divided into 3 Secondary read

​ int read(byte) : Read by the length of an array , Returns the actual read byte length , The data is stored in an array

​ int read(byte , offset , len) : Read the specified length of data in the stream , And store it in a designated location ,

​ available() : Returns the length of bytes left in the stream , If you have finished reading , Then return to 0

​ skip(long n ): Discard the specified byte length , Read from next

 File file = new File("d:/aaa.txt");
FileInputStream fis = new FileInputStream(file);
byte [] b= new byte[10];
StringBuffer sb = new StringBuffer();
// The length of each read , b: An array of data 
int len = 0;
while((len = !=-1){
sb.append( new String(b,0,len));
 public static void read2() throws IOException {
// InputStream Abstract class 
InputStream is = new FileInputStream("d:/aaa.txt");
// Discard the first two bytes 
System.out.println(" How many bytes are left :"+ is.available());
// Continue to read the following bytes using the byte array 
byte [] b = new byte[10];
int len =,1,4);
// Display all the data read in the array 
// Converts the contents of an array to a string There is no conversion for empty content 
System.out.println(new String(b));

The document says : Write out the data in memory to disk

Construction method :

new FileOutputStream(File/String ) : Construct a write out stream of file objects , Default override write out

new FileOutputStream(File/String , append): Construct a write out stream of file objects ,

append: It means to append data to the original file , false : Cover

Common methods :

​ void write(int) : Write a byte

​ void writer(byte []) : Write an array of bytes , Here you need to specify the encoding format of the array “UTF-8”

​ void writer(byte[] , offerset,len) : Write an array of bytes , Specifies the length and subscript of the array . Start with the subscript of the array ,len It means the length of writing

​ flush() : Empty cache , When using buffered streams , Force the buffer to empty .

 // Write out the data in memory to a file If the file doesn't exist , Automatically created , Default override write true: Additional 
FileOutputStream fos = new FileOutputStream("d://aaa.txt" ,true);
String str=" The weather is not bad today ";
// Write a string Strings can be converted into byte arrays Or array of characters 
// Write the specified length 
fos.write(str.getBytes("UTF-8"),0,3); // Write the front of the array 2 Bytes 
// Empty cache 
// Closed flow 
System.out.println(" Write success ");

File replication :

Will file ( picture , Text , video ) Copy from one directory to another , The data length remains unchanged , Copy by reading and writing files

The copying process : Read data from the source file , Then the data is exported to the target file .

* Single byte copy
* @param srcFile Source file
* @param disFile Target file
public static void copyFile(File srcFile, File disFile){
FileInputStream fis=null;
FileOutputStream fos =null;
try {
// Source file input stream 
fis = new FileInputStream(srcFile);
// Target file output stream 
fos = new FileOutputStream(disFile);
int n=0;
while( (n !=-1){
// Will read n Write to In the target file 
System.out.println(" Replication success ..");
} catch (FileNotFoundException e) {
} catch (IOException e) {
} finally{
// Whether or not there is an exception Will shut down the flow 
try {
} catch (IOException e) {
* Assignment of an array of bytes
* @param src source address
* @param disc Destination address
public static void copyFile(String src,String disc){
FileInputStream fis = null;
FileOutputStream fos = null;
try {
// establish Byte input stream 
fis=new FileInputStream(src);
fos = new FileOutputStream(disc);
int len=0;
byte [] b = new byte[1024];
while( (len= !=-1){
// Write Actual read length , To avoid extra bytes on the last write 
System.out.println(" Replication success ");
} catch (FileNotFoundException e) {
} catch (IOException e) {
} finally{
try {
} catch (IOException e) {

Exercise one : take d://mywork A file in a directory Assign values to the e://mywork ​ // among Directory contains subdirectories Copy the same file directory ​ // Ideas : 1、 First traverse the folder , Recursively call , ​ // If it is a file, get the parent path of the file first , If it doesn't exist , create ​ // If there is a path, copy the file directly ( Call the assignment method ) ​ // 2、 Create a parent path using mkdirs() ​ // for example d://mywork/aaa/1.txt ​ // The goal is : e://mywork/aaa/1.txt You can replace... With a string d: Replace e: ​ // Let's see if this path exists , If it doesn't exist create

Character stream

​ Character streams are used to read and write files that store characters , In one character , Read the characters one by one file , The common classes are as follows Reader or Writer For the parent class , Operation of files using and

​ Reading documents :FileReader

Common methods :

​ new FileReader(path): Build character input stream through file path

​ new FileReader(File): Building character input streams from file objects

  • ​ int read() : Read a character , Return character's int type

  • ​ int read(char ): Read the length of the character array , Returns the actual read character length , The data is stored in a character array

  • ​ int read(char offerset len): Read an array of specified character length , return The length of the actual read character , The data is stored in a character array

  • ​ mark(int) : Mark the current position in the stream ( Where did you read it )

  • ​ markSupported(): Determine if the stream supports mark operation

  • ​ reset(): Reset stream data ,( It can be read from the beginning )

  • ​ skip(long) : Discard the specified length character

Reading character files

 // 1、 Create character input stream 
try {
FileReader reader = new FileReader("d:/myfile.txt");
// Discard characters 
// Read a character 
// Read a character array length 
char [] c = new char[10];
System.out.println(" Actual length :";
System.out.println(new String(c));
// Continue to read 
int len =,0,5);
System.out.println(" A character array :"+ Arrays.toString(c));
System.out.println(" Read the number of characters of specified length :"+new String(c,0,len));
// Reset character stream 
// reader.reset();
// System.out.println(" Reset and continue reading :"+;
//System.out.println(" Whether marker characters are supported :"+reader.markSupported());
// Closed flow , The object cannot be used later 
} catch (FileNotFoundException e) {
} catch (IOException e) {

Writing documents : Write out the memory data to a file , In the process of writing, you can Overlay writing can also be added ,FileWriter Class creation object process

​ new FileWriter(String ): Specify the address for writing out the document

​ new FileWriter(String ,append) : Specify the address for writing out the document , Set whether to append write out ,true Indicates append ,false Indicates coverage

​ new FileWriter(File) Specifies the write out file object

​ new FileWriter(File ,append); Point to write out the file object , Set whether it can be appended

Common methods :

​ writer(int) : Write a character

​ writer(String): Write a string

​ writer(char [] ): Write an array of characters

​ writer(char [] , offerset , len): Write an array of characters of specified length

​ flush() : Refresh buffer ,

​ close(): Turn off buffering

​ append(c) : Adds the specified character to this stream

 // 1、 Create a file and write out the stream FileWriter
try {
// file does not exist , Automatically create , But it doesn't create a directory 
File file = new File("d://myabc/aaa.txt");
// Determine that the file directory does not exist , Create a directory first 
// Create the directory 
FileWriter writer = new FileWriter("d://myabc/aaa.txt");
// Write one character asci
// Write string 
// Write a string of specified length 
writer.write("abcdef",0,3); // Write abc
char [] c = {'L','O','L'};
// Write character array 
System.out.println(" Write success ");
} catch (IOException e) {

Close and refresh :

For those with buffers Functional writing stream , You need to refresh the buffer first , To write the data out , If you don't refresh it, you can't write it normally in the end . Write the stream. If you refresh, you can continue to write , If it is closed, you can't continue to write .

Interview questions flush and close The difference between ?

flush: Refresh buffer , Stream can continue to use

close: Refresh buffer first , Then release the system resources , It can't be used after closing

 try {
FileWriter writer = new FileWriter("1.txt");
writer.write(" brush ");
writer.write(" new ");
writer.write(" Turn off ");
writer.write(" close "); // So this throws an exception , Stream closed
} catch (IOException e) {

About line breaks

A carriage return \r And line breaks \n : A carriage return : Go back to the beginning of the line (return). A newline : The next line (newline). Line breaks in the system : Windows In the system , Each line ends with enter + Line break , namely \r\n ; Unix In the system , Each line ends with Line break , namely \n ; Mac In the system , Each line ends with enter , namely \r . from Mac OS X Start with Linux Unified .


One 、 Packaging flow

Definition : On the basis of the original byte stream or character stream , A stream that is reprocessed to improve reading and writing efficiency , It's called packaging flow / Processing flow

1、 Cache byte stream BufferedInputStream 、BufferedOutputStream

​ Because the original stream is when the file is read and written Low efficiency ( The operation file itself takes up more resources ), You can improve the efficiency of reading and writing by creating buffers , Will read / The written data line is put into the buffer , After reaching a certain number of buffer reads again / Write

​ mark(readLimit) And reset() usage

among reset Not to be used alone , must mark(readLimit) ,readLimit Indicates the maximum read limit after the tag , But what is read after marking is similar to BufferedInputStream The buffer size is related to , The ratio is determined by the upper limit , That is to say, if the read content exceeds the upper limit, it can be reset to mark The location of .

public static void main(String[] args) throws IOException {
// Create a buffer stream 
InputStream is = new FileInputStream("d:/myfile.txt");
BufferedInputStream bis = new BufferedInputStream(is);
// Do you support mark or reset
// Reset 
bis.mark(3); // pos Mark back three You can read the maximum byte limit 
System.out.println(" Read again :"+(char);
System.out.println(" Read again :"+(char);
System.out.println(" Read again :"+(char);
System.out.println(" Read again :"+(char);
bis.reset(); // here After reset Return to 3 A previous position 
// Output after reset 
int n =0;
while( (n = !=-1){
System.out.println(" After reset ;"+(char)n);
// Closed flow 

2、 Cache character stream (BufferedReader 、BufferedWriter)

 public static void main(String[] args) throws IOException {
// Buffer character stream It can be read line by line 、 Write 
BufferedReader br = new BufferedReader(new FileReader("d:/ Niche sites .txt"));
// Read a line 
// System.out.println(br.readLine());
// System.out.println(br.readLine());
// System.out.println(br.readLine());
String s = null; // The data read is empty You don't need to read 
while( (s = br.readLine()) !=null){
// Buffer write stream 
FileOutputStream pw = new FileOutputStream("d:/abcd.txt");
// Because the byte stream cannot be put directly into Character buffer , It needs to be converted into a character stream Use the transform stream and you can specify the encoding format 
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(pw));
bw.newLine();// Start a new line ( Line break )
bw.write(" This is the way to test the transformation flow ");

3、 Print stream ( Output stream ) PrintWriter 、PrintStream

 public static void main(String[] args) throws FileNotFoundException {
// Print stream , Provide some printout methods 
PrintWriter pw = new PrintWriter("d:/abcd.txt");
pw.println('a');// Line to print 
//System.out Byte print stream PrintStream

4、 Data byte stream DataInputStream、DataOutputStream

They are used to read in and write out Java Basic data type data to file or other device side , They also belong to the packaging stream

DataOutputStream Common methods

  • ​ writerByte(byte): Write a byte to a device or file

  • ​ writerChar(char): Write a character to a device or file

  • ​ writerInt(int): Write a 4 Bytes of int To device or file

  • ​ writer(boolean): Write a boolean Type to device or file

  • ​ writerDouble(double): Write a double Type to device or file

  • ​ writerFloat(float): Write a float Type to device or file

  • ​ writerLong(long): Write a long Type to device or file

  • ​ writerShort(short): Write a short Type to device or file

  • ​ writerUTF(String): Write a string type to the device or file

DataInputStream: Read the data of the specified file , Can read data types

  • ​ int readInt() : Read a int type

  • ​ short readShort(): Read a short type

  • readByte(): Read a byte type

  • ​ read(): Read a byte type

  • ​ readDouble(): Read a double type

  • ​ readFloat(): Read a float type

  • ​ readChar(): Read a character type

  • ​ readBoolean(): Read a boolean type

  • ​ readLong() : Read a long type

 public static void main(String[] args) throws IOException {
// Create a data write out stream 
DataOutputStream dos = new DataOutputStream(
new FileOutputStream("d:/data.txt"));
// Write a int type Write... In turn 4 Bytes 
// close 
// Read the file Create a data read in stream , You need to read it in the order you write it 
DataInputStream dis = new DataInputStream(
new FileInputStream("d:/data.txt"));
// Read a int type ( Read in turn 4 Bytes )
int num = dis.readInt();
System.out.println(" Read data :"+ num);
System.out.println(" Reading data :"+dis.readBoolean());

5、 Converted flow

​ The conversion stream is a bridge that converts bytes into character streams , You can also specify the encoding format during conversion . InputStreamReader and OutputStreamWriter

 public static void main(String[] args) throws IOException {
// Bytes flow into a stream of characters 
InputStream is = new FileInputStream("d:// Niche sites .txt");
InputStreamReader isr = new InputStreamReader(is);
// Buffer flow Reading data 
BufferedReader br = new BufferedReader(isr);
// Read a line 
String str =null;
while( (str= br.readLine()) !=null){
// Closed flow 
 public static void main(String[] args) throws IOException {
// establish Converting bytes into characters Write the stream FileOutputStream os =
FileOutputStream fos = new FileOutputStream("d://data.txt");
// Specified encoding GBK Format a Chinese character occupies 2 Bytes UTF-8 Format a Chinese character occupies 3 Bytes 
OutputStreamWriter osw = new OutputStreamWriter(fos,"UTF-8");
// In the form of buffering 
BufferedWriter bw = new BufferedWriter(osw);
bw.write(" Hello ");
bw.write(" my bad ");

6、 Random byte stream

RandomAccessFile It's a random byte stream , It's a readable and writable stream , Specify the mode of the object during file operation (model) after , You can read data or write data

Realization DataInputStream and DataOutputStream class

Constructors :

RandomAccessFile rm = new RandomAccessFile(File ,mode);

​ RandomAccessFile rm = new RandomAccessFile(String ,mode);

mode Patterns representing objects

r: Indicates that the object can only be read Can't write

rw/rws/rwd : It means that we should Objects are readable and writable ;

public static void main(String[] args) throws IOException {
// Create readable The flow of 
RandomAccessFile reader = new RandomAccessFile("d://data.txt","r");
// Create readable and writable The flow of 
RandomAccessFile writer = new RandomAccessFile("d://data-1.txt","rw");
// The process of reading and writing is the same as before 
byte [] b= new byte[10];
int len=0;
while( (len = !=-1){
writer.write(b , 0 , len);
System.out.println(" Replication success ");
// Closed flow 

skipByte and seek The difference between

 // Skip byte read 
RandomAccessFile raf = new RandomAccessFile("d:/data.txt","rw");
// skip 2 Bytes 
System.out.println((char)raf.readByte()); //3
System.out.println(" Current offset :"+raf.getFilePointer());//3
// Throw away again 1 Bytes From the current position Move back 1 position 
System.out.println(" Modified offset "+raf.getFilePointer());//4
System.out.println(" Read data after offset :"+(char)raf.readByte()); //5
// seek usage 
RandomAccessFile raf2 = new RandomAccessFile("d:/data.txt","rw");
// Set the current read position , from 0 Start calculating , Appoint n , From n Next byte of Read;
System.out.println("seek Later data :"+(char)raf2.readByte());//3; // Again from 0 Start Set the offset to 1 
System.out.println(" Modified offset "+raf.getFilePointer());//1
System.out.println("seek Later data :"+(char)raf2.readByte())//2

7、 Object serialization stream

​ An object stream is also known as a serialization stream , A stream of bytes used to store and read objects , It also belongs to packaging flow

Serialization and deserialization

​ Put the object in memory (Object, Set class, etc ) Save to disk 、 Network media 、 The process of other settings , And can obtain the disk file in the right time / Network data , This process is the serialization and deserialization of objects .

Why do you need to serialize and deserialize ?

​ Text information stored in previous files , This is not convenient for data classification and operation , If you can read and write objects directly, you can greatly improve the programming efficiency , And to maximize the integrity of the object .

Java-IO There are two ways to realize object serialization in :

  1. Realization Serializable Interface

  2. Realization Externalizable Interface

    Serializable Interface

    Object needs to implement the interface , But it doesn't have any way to implement it , There is only one unique identifier used to mark the serializability of the class . Any class that needs serialization must mark the variable

    public class User implements Serializable {
    // For a unique representation that distinguishes other classes 
    private static final long serialVersionUID = 1L;
    private int uid;
    private String name;
    private String password;
    // Some properties cannot be serialized 
    public int getUid() {
    return uid;
    public void setUid(int uid) {
    this.uid = uid;
    public String getName() {
    return name;
    public void setName(String name) { = name;
    public String getPassword() {
    return password;
    public void setPassword(String password) {
    this.password = password;
    public String toString() {
    return "User{" +
    "uid=" + uid +
    ", name='" + name + '\'' +
    ", password='" + password + '\'' +
     // Create a serialized stream of objects From memory to files 
    ObjectOutputStream oos = new ObjectOutputStream(
    new FileOutputStream("d:/user.txt"));
    User user= new User();
    // Serializing objects 
    // Closed flow 
    // Deserialization : Put the data in the file Read it into memory again , Need a read stream ObjectInputStream
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream("d://user.txt"));
    // Deserialization should be read-only once as much as possible ( You can read it many times , Read in as you write )
    Object obj = ois.readObject();
    if(obj instanceof User){
    User u = (User)obj;
    System.out.println(" The result of deserialization :"+u);
    // Closed flow 

​ problem : Whether the serialized properties can be customized , Here we can use mode two , Realization Externalizable, And rewrite the two methods Interface inherited from , On the basis of it, two new methods are added :readExternal(ObjectInputStream) and writeExternal(ObjectOutputStreawm) , Custom properties that need to be serialized

public interface Externalizable extends

Externalizable Interface

public class Student implements Externalizable {
private int id;
private String name;
private String sex;
public int getId() {
return id;
public void setId(int id) { = id;
public String getName() {
return name;
public void setName(String name) { = name;
public String getSex() {
return sex;
public void setSex(String sex) { = sex;
// Custom serializable properties 
public void writeExternal(ObjectOutput out) throws IOException {
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { = in.readInt(); = in.readUTF();
public Student(int id, String name, String sex) { = id; = name; = sex;
public Student( ) {
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
 public static void main(String[] args) throws IOException, ClassNotFoundException {
// Create a serialization class 
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream("d:/stu.txt"));
// Creating students 
List<Student> list = new ArrayList<>();
list.add(new Student(1001," Zhang Fei "," male "));
list.add(new Student(1002," Liu bei "," male "));
list.add(new Student(1003," Little Joe "," Woman "));
// Serialize the collection 
// close 
// Deserialization 
ObjectInputStream ois = new ObjectInputStream(
new FileInputStream("d:/stu.txt"));
// read 
Object obj = ois.readObject();
if(obj instanceof List){
List<Student> list2 = (List<Student>)obj;
for(Student s : list2){
// Closed flow 

​ problem : Which properties cannot be serialized

​ * 1、 Class static Decorated properties cannot be serialized

​ 2、 The properties in the class are transient Decorated cannot be serialized for example transient private Integer age = null;

​ 3、 Realization Externalizable The properties of the class of the interface cannot be serialized , Serializable properties must be written manually .


One 、 Compressed and decompressed streams of files

1、 Why you need to use compressed files

File compression usage scenarios : When you need to operate multiple files during file upload or download , If it takes a long time to replicate one by one , And it's complicated ,javaAPI Provides a kind of compression / How to decompress files , You can package multiple files into one file (.zip)

package :

Common classes : ZipEntry: Represents each entity file in the compressed file

​ ZipFile: Represents a compressed file object

​ ZipOutputStream: Represents the compressed file output stream , Used to write ordinary documents to zip In file

​ ZipInputStream: Represents the input stream of the decompressed file , Used to read zip Every entity in the file ZipEntry there abcd.txt It's just one. ZipEntry

2、 Compress file steps

a、 Create the input stream that needs to be compressed (InputStream )

​ b、 The path where the compressed package is created , And specify the compressed file name , Create at the same time ZipOutputStream Output stream

​ c、 Put the file object Add to ZipOutputStream In the entity of ( You can also specify the compressed entity name )

​ d、 File replication

​ e、 Closed flow

 public static void main(String[] args) throws IOException {
// 1、 Create a file object 
File file = new File("d:/ Niche sites .txt");
// 2、 Create an input stream for the file 
FileInputStream fis = new FileInputStream(file);
// 3、 Create a compressed file stream ( Output stream )
ZipOutputStream zos = new ZipOutputStream(
new FileOutputStream("d:/"));
// Add files to the package , And can customize the file name 
zos.putNextEntry(new ZipEntry(" Niche sites .txt "));
// Set comments for the package 
zos.setComment(" This is the comment for the compressed package ....");
// File replication 
int len = 0;
byte [] b = new byte[1024];
while( (len = !=-1){
System.out.println(" File compression successful ");

Compress multiple files

* Compress a folder myfile
* @param args
public static void main(String[] args) throws IOException {
// Build the output stream of the compressed package 
ZipOutputStream zos = new ZipOutputStream(
new FileOutputStream("d:/"));
File file=new File("d:/myfile");
File [] files = file.listFiles();
for(File f : files){
// Construct the input stream for each file 
FileInputStream fis = new FileInputStream(f);
putZipFile(fis, zos ,f.getName());
System.out.println(f.getName()+" File compression successful " );
// Turn off the compressed stream 
* Put the file into the compressed stream
* @param fis
* @param zos
* @param entryName
* @throws IOException
public static void putZipFile(InputStream fis ,
ZipOutputStream zos,
String entryName) throws IOException {
// Add files to the package , And can customize the file name 
zos.putNextEntry(new ZipEntry(entryName));
// Set comments for the package 
zos.setComment(" This is the comment for the compressed package ....");
// File replication 
int len = 0;
byte [] b = new byte[1024];
while( (len = !=-1){
System.out.println(" File compression successful ");

3、 Decompress the file step

​ Unzip the file is to put a .zip The content of the document , Copy to file , Need to use ZipInputStream

​ Key points of decompressing files : Get each entry of the extracted file ZipEntry The input stream of , Write out the input stream to the specified location .

​ How to get the input stream : ZipFile object It means a zip file step :

​ a、 According to file path establish ZipInputStream

​ b、 Create according to the file path ZipFile object

​ c、 Loop through the items of each day , Get its ZipEntry

​ d、 obtain ZipEntry The input stream of

​ e、 Copy the file to the specified location

 public static void main(String[] args) throws IOException {
//1、 establish ZipInputStream
ZipInputStream zis = new ZipInputStream(
new FileInputStream("d:/"));
// 2、 establish ZipFile object 
ZipFile zipFile = new ZipFile("d:/");
// 3、 obtain zip Entity in 
ZipEntry en = null;
while( (en= zis.getNextEntry())!=null){
//4、 Get every en The input stream of ( The key )
InputStream is = zipFile.getInputStream(en);
copyFile(is ,"d:/my",en.getName());
* Through the input stream Copy the file to the specified directory
* @param is Input stream
* @param path The path where the file is stored
* @param fileName file name
public static void copyFile(InputStream is , String path , String fileName) throws IOException {
File file = new File(path);
// Determine whether the directory exists , If it doesn't exist establish 
FileOutputStream fos = new FileOutputStream(path+File.separator+fileName);
int len = 0 ;
byte [] b = new byte[1024];
while( (len = !=-1){
System.out.println(" Decompress successfully ");

Two 、Java The multithreading

1、 Basic concept of thread

​ 1.1 Definition

​ Introduce threads : Open the task manager in the calculation , There are many entries , Each entry corresponds to an application , This app we call “ process ” , Every process takes up CPU Resources and memory , In this process Contains multiple tasks , They can “ meanwhile ” function , Each task here is called ” Threads “

​ If you will Java Of An application is compared to a process , Then the multiple execution processes it contains is a Threads .

​ Multithreading in life : You're playing games right now , You can talk to each other ( Mutual spraying ), You can also control the game , You can also greet your teammates . Playing games is a process , Your different operations are a single thread for the game itself , If you can operate at the same time , The game can support Multithreading .

​ process : A process is a separate application in a computer , The process is dynamic , Operational

​ Threads : A single task that runs in a process , It's a subroutine of a process

​ Program : A program is a collection of data descriptions and operation codes , It's the code that does something , It's static Multithreading : Multiple subtasks in a process , There will be resource preemption in multithreading , In a single core CPU At the same time point, only one thread can run under a process . Threads will compete with each other for resources

CPU Resource allocation Computers can run multiple applications ( Multi process ), At the same time ,CPU Only one task can be performed , Due to the time slice switching is very fast , You can't even notice that “ wait for ” The situation of , If the computer appears “ stuck ” You can task resources are not available and waiting .

Single thread running process : The program has only one running line , Be consistent from the beginning to the end Multithreading : There can be multiple finishing tasks , It's hard to predict which one ends first How to create a multithreaded program ?

Mode one : Inherit Thread class

a、 Define a class inheritance Thread class , rewrite run Method

b、 Create objects of this class , And call start Method

public class MyThread extends Thread {
public void run() {
for(int i=0;i<100;i++){
// Get the current thread name 
 public static void main(String[] args) {
// Creating thread objects 
MyThread my = new MyThread();
// Open thread 
for(int i = 0 ;i < 100 ;i ++){
System.out.println(" Main thread i-----"+i);
// Conclusion : For multi threads, there will be resource preemption in their execution process , Who gets it first cpu resources , Who will carry out 

Mode two : Realization Runnable Interface

a、 Create a class to implement an interface

public class MyThread2 implements Runnable {
public void run() {
for(int i = 0;i<100;i++){
// Get current Thread name of the thread 

b、 With the help of Thread Class opens the thread

 public static void main(String[] args) {
// because MyThread2 Not associated with threads , You need to start with thread class 
// Create the task class that the thread needs to execute 
MyThread2 my = new MyThread2();
Thread th = new Thread(my," Threads A");
// Start one more 
Thread th2 = new Thread(my," Threads B");

problem : The difference between the above two creation threads ?

1、 The inheritance method is applicable to those without direct parents , Relatively simple , It's a single inheritance , In the way of interface, the target class can inherit the class and implement other interfaces

2、Runnable The implementation method is applicable to Resource sharing , Thread synchronization .

3、Runnable The implementation is not a thread class , It's the target class that implements the thread (Target)

Add : There are not only two ways to create threads , You can also create threads and Thread pooling .

2、 The life cycle of a thread

Life cycle definition

The whole process of thread from creation to destruction , It's called the thread lifecycle , For example, the life cycle of a person is the whole process from birth to death. The process that will be experienced in the process includes born , Grow up , Grow old , Leave It's all a person has to go through .

The phases of the life cycle

1、 Freshman state : The program creates the thread ( Instantiate objects )

2、 Ready state ( Operational state ) : When a thread calls an object start() After the method , You can seize cpu resources , But not immediately run Method

3、 Running state : When resources are seized , Run immediately run Method

4、 Blocked state : At run time , Thread encountered blocking event ( Thread to sleep ,wait ,IO operation ,join Operation etc. ), It's blocked

5、 Death state : Thread finished running , Or abnormal interruption , here CPU Resources released

本文为[Fu Yao laughs at cangming]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云