Java advanced: Java file - & - IO, in-depth interview with linux kernel architecture

Posted by ryanbutler on Sat, 18 Dec 2021 15:35:23 +0100

    fis.close();
}

/*
 * Method to realize file replication
 *  1. Byte stream reads and writes a single byte
 */
public static void copy_1(File src,File desc)throws IOException{
    FileInputStream fis = new FileInputStream(src);
    FileOutputStream fos = new FileOutputStream(desc);
    int len = 0 ;
    while((len = fis.read())!=-1){
        fos.write(len);
    }
    fos.close();
    fis.close();
}

}

## 3, Character buffer stream

### 1. Character output buffer stream BufferedWriter

- ```java.io.BufferedWriter```inherit Writer
- **Write method: write ()** ,Single character,Character array,character string
- **Construction method:**```BufferedWriter(Writer w)```: Pass any character output stream, and whoever passes it will be efficient
- Character output stream that can be passed: **FileWriter, OutputStreamWriter**
```java
public class BufferedWrierDemo {
    public static void main(String[] args) throws IOException{
        //Create character output stream and encapsulate file
        FileWriter fw = new FileWriter("c:\\buffer.txt");
        BufferedWriter bfw = new BufferedWriter(fw);

        bfw.write(100);
        bfw.flush();
        bfw.write("Hello".toCharArray());
        bfw.flush();

        bfw.write("Hello");
        bfw.flush();

        bfw.write("I'm fine");
        bfw.flush();

        bfw.write("Hello, everyone");
        bfw.flush();

        bfw.close();
    }
}

2. Character output buffer stream BufferedWriter - special method newLine

  • void newLine(): write newline
  • newLine(): line break in text, \ R \ NIS also a line break in text
  • The method is platform independent

windows \r\n ; Linux \n

  • The newLine() run result and the operating system are interrelated
  • JVM: the installed version is Windows, and what newLine() writes is \ r\n; The Linux version is installed, and newLine() writes * * \ n**

3. Character input stream BufferedReader

(1) Overview

  • java.io.BufferedReader inherits the Reader, reads text from the character input stream and buffers each character, so as to realize efficient reading of characters, arrays and lines
    Read function: read(), single character, character array
    Construction method: BufferedReader(Reader r): any character input stream can be used, including FileReaderInputStreamReader

(2) BufferedReader's own functions

  • String readLine(): read a text line \ r\n, read a text line, a string containing the contents of the line, without any line terminator, and return null if the end of the stream has been reached

Methods to get content generally have return values
int: negative numbers are not returned
Reference type: null returned if not found
boolean: false if not found

public class BufferedReaderDemo {
    public static void main(String[] args) throws IOException {
        int lineNumber = 0;
        //Create a character input stream buffer stream object, construct a method to transfer the character input stream, and wrap the data source file
        BufferedReader bfr = new BufferedReader(new FileReader("c:\\a.txt"));
        //Call the method readLine() of the buffer stream to read the text line
        //Loop to read the text line, and the end condition readLine() returns null
        String line = null;
        while((line = bfr.readLine())!=null){
            lineNumber++;
            System.out.println(lineNumber+"  "+line);
        }
        bfr.close();
    }
}

4. Character stream buffer copy text file

/*
 *  Using the buffer stream object, copy the text file
 *  Data source BufferedReader+FileReader read
 *  Data destination BufferedWriter+FileWriter write
 *  Read a line of text, read a line, write a line, write a new line
 */
public class Copy_1 {
    public static void main(String[] args) throws IOException{
        BufferedReader bfr = new BufferedReader(new FileReader("c:\\w.log"));   
        BufferedWriter bfw = new BufferedWriter(new FileWriter("d:\\w.log"));
        //Read a line of text, read a line, write a line, write a new line
        String line = null;
        while((line = bfr.readLine())!=null){
            bfw.write(line);
            bfw.newLine();
            bfw.flush();
        }
        bfw.close();
        bfr.close();
    }
}

4, Serialized stream and deserialized stream

1. General

  • Object serialization: the data in the object is written to the file in the form of stream. The saving process is called writing out the object. ObjectOutputStream writes the object to the file to realize serialization
  • Object deserialization: in the file, read out the object in the form of stream, read the object, and ObjectInputStream reads out the file object

2. Realization

  • ObjectOutputStream: write objects to achieve serialization
    • Construction method: objectoutputstream (OutputStream out): pass any byte output stream
    • void writeObject(Object obj): writes out the object
  • ObjectInputStream: read the object and realize deserialization
    • Construction method: ObjectInputStream(InputStream in): pass any byte input stream. The input stream encapsulates a file and must be a serialized file
  • Object readObject(): reads objects
//Define class
public class Person implements Serializable{
   //ellipsis
    }               
}

 public class ObjectStreamDemo {
    public static void main(String[] args)throws IOException, ClassNotFoundException {
        writeObject();
        readObject();
    }

    //ObjectOutputStream
    public static void writeObject() throws IOException{
        //Create byte output stream and encapsulate file
        FileOutputStream fos = new FileOutputStream("c:\\person.txt");
        //Create an object that writes out the serialized stream of the object, and the constructor passes the byte output stream
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        Person p = new Person("lisi",25);
        //Call the method writeObject of the serialized stream to write out the object
        oos.writeObject(p);
        oos.close();

    //ObjectInputStream
    public static void readObject() throws IOException, ClassNotFoundException{
        FileInputStream fis = new FileInputStream("c:\\person.txt");
        //Create a deserialization stream and pass the byte input stream in the construction method
        ObjectInputStream ois = new ObjectInputStream(fis);
        //Call the method readObject() of the deserialization stream to read the object
        Object obj =ois.readObject();
        System.out.println(obj);
        ois.close();
    }
}

3. Details

(1) transient keyword

  • Function: attributes modified by transient will not be serialized
  • The transient keyword can only modify member variables

(2) Static cannot be serialized

  • Reason: serialization is the persistent storage of object data; Static things do not belong to objects, but to classes

(3) Serializable interface

  • Function: mark the class to be serialized. There are no abstract methods in this tag; Only objects of classes that implement the Serializable interface can be serialized

4. Serial number conflict in serialization

  • Problem: when a class implements the Serializable interface, it creates an object and writes the object to a file, and then changes the source code (for example, change the modifier of the member variable from private to public), an exception will be reported when reading the object from the file again

  • Reason: once the source code is modified and the class file is recompiled, the serial number will be recalculated according to the class members, so that the serial number in the newly compiled class file is different from that in the original file

  • Solution: you need to make a lifelong serial number! You need to customize the serial number in serialization

private static final long serialVersionUID = 1478652478456L;
// In this way, the serialVersionUID value generated each time the class is compiled is fixed
//Class, the compiler will not calculate the serial number

5, Print stream

1. General

  • Print streams add the function of output data, so that they can easily print various data value representations

2. Classification of print streams

  • Byte print stream
  • Character print stream PrintWriter

3. Method

  • void print(String str): output any type of data,
  • void println(String str): output any type of data and automatically write to the line feed operation

4. Features

  • This flow is not responsible for the data source, but only for the data destination
  • You can manipulate any type of data. (boolean, int, long, float, double)
  • Print stream, you can turn on the automatic refresh function
    Two conditions are met:
    • Use a specific construction method to turn on the automatic refresh of the print stream. The output data must be aimed at the stream object: OutputStreamWriter
    • You must call one of the three methods println, printf and format to enable automatic refresh
  • Add functionality for other output streams
  • IOException will never be thrown, but other exceptions may be thrown

5. Construction method

  • Is the output destination of the print stream
  • PrintStream construction method
    • Receive File type, receive string File name, and receive byte output stream OutputStream
  • PrintWriter construction method
    • Receive File type, receive string File name, receive byte output stream, and receive character output stream Writer

6. Print character array

  • println array. Only when printing the character array is the print content, and the rest are the address of the array
  • Because the api defines the method of printing character arrays, its bottom layer is to traverse the elements in the array, while other methods of printing arrays are to program the array Object as Object, and its bottom layer is to program the Object as String, calling String s = String valueOf(x); method

7. Use the print stream to copy the text file

/*
 * Print stream for text replication
 * Read data source BufferedReader+File read text line
 * Write data destination PrintWriter+println auto refresh
 */
public class PrintWriterDemo1 {
    public static void main(String[] args) throws IOException{
        BufferedReader bfr = new BufferedReader(new FileReader("c:\\a.txt"));
        PrintWriter pw = new PrintWriter(new FileWriter("d:\\a.txt"),true);
        String line = null;
        while((line = bfr.readLine())!=null){
            pw.println(line);
        }
        pw.close();
        bfr.close();
    }
}

6, Standard input and output streams

1. General

  • Standard input stream: system In refers to keyboard input by default
  • Standard output stream: system Out output to display

2. Inheritance

  • PrintStream extends FilterOutputStream
  • FilterOutputStream extends OutputStream

3. Cases

public class StandardIO {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String s;
        // The read method of standard input stream, when reading keyboard data, when there is no keyboard input data at present
        // read will block the current thread so that it cannot end. Only custom protocols can end the standard input stream
        while((s = br.readLine()) != null) {
            //Custom protocol, receiving user input when user input 886 ends
            if("886".equals(s)) {
                break;
            }
            System.out.println("Output:" + s);
        }
        br.close();
    }
}

7, IO stream summary

  • Byte stream
    • Byte input stream InputStream
      • FileInputStream the byte input stream of the operation file
      • BufferedInputStream efficient byte input stream
      • ObjectInputStream deserialization stream
    • Byte output stream OutputStream
      • FileOutputStream operates on the byte output stream of a file
      • BufferedOutputStream efficient byte output stream
      • ObjectOuputStream serialized stream
      • PrintStream byte print stream
  • Character stream
    • Character input stream Reader
      • FileReader operates on the character input stream of the file
      • BufferedReader efficient character input stream
      • InputStreamReader input operation conversion stream (encapsulating byte stream into character stream)
    • Character output stream Writer
      • FileWriter operates on the character output stream of a file
      • BufferedWriter efficient character output stream
      • OutputStreamWriter the conversion stream of the output operation (encapsulating the byte stream into a character stream)
      • PrintWriter character print stream
  • method:
    • Data reading method:
      • read() is a method of reading one byte or character at a time
      • read(byte[] char []) is a method to read array data one at a time
      • readLine() method for reading one line of string at a time (BufferedReader class specific method)
      • readObject() reads an object from the stream (ObjectInputStream specific method)
    • Write data method:
      • write(int) writes one byte or character at a time to the file
      • write(byte[] char []) writes array data to the file one at a time
      • write(String) writes the string contents to the file one at a time
      • writeObject(Object) writes the object to the stream (ObjectOutputStream class specific method)
      • newLine() writes a newline symbol (a method unique to the BufferedWriter class)
  • The process of writing data to a file
    1. Create an output stream object
    2. Write data to file
    3. Close the output stream
  • The process of reading data from a file
    1. Create an input stream object
    2. Read data from the file
    3. Close the input stream
  • File copy process
    1. Create input stream (data source)
    2. Create output stream (destination)
    3. Read data from the input stream
    4. Write the data to the destination through the output stream
    5. Close the flow

File class

  • method
  • Get file name getName()
  • Get file absolute path getAbsolutePath()
  • Get file size length()
  • Get all File objects in the current folder File[] listFiles()
  • Determine whether it is a file (isfile)
  • Determine whether it is a folder (isdirectory)
  • Create folder mkdir() mkdirs()
  • Create file (createnewfile)
  • abnormal
    • try... Catch... finally catch exception handling

Data sharing

Receiving method: you can get it for free by stamping here At the same time, you can also "whore" to a detailed explanation of the Redis transaction source code.

1. Big algorithm factory -- byte jump interview question

2. 2000 pages of Internet Java interview questions

3. High order essential, algorithm learning

ir() mkdirs()

  • Create file (createnewfile)
  • abnormal
    • try... Catch... finally catch exception handling

Data sharing

Receiving method: you can get it for free by stamping here At the same time, you can also "whore" to a detailed explanation of the Redis transaction source code.

1. Big algorithm factory -- byte jump interview question

[external chain picture transferring... (img-ED9BhwNf-1630207871730)]

2. 2000 pages of Internet Java interview questions

[external chain picture transferring... (img-4tmlefjd-163027871732)]

3. High order essential, algorithm learning

Topics: Java Linux Back-end Interview Programmer