< Notes > Java SE-06 Java SE IO

Keywords: Java encoding network socket

06 Java SE IO

By Kevin Song

  • Overview of 06-01 IO Flow
  • 06-02 Byte Stream and Character Stream
    • 06-02-01 character stream
    • 06-02-02 byte stream
    • 06-02-03 Conversion Flow
    • Operating Rules of 06-02-04 IO Flow
  • 06-03 File class
  • 06-03-01 Recursion
  • 06-04 Properties Collection
  • 06-05 Other IO Classes
    • 06-05-01 Print Stream
    • 06-05-02 Sequence Stream
    • 06-05-03 ObjectStream
    • 06-05-04 Random AccessFile class
    • 06-05-05 pipeline flow
    • 06-05-06 DataStream
    • Stream of 06-05-07 Operational Array
    • 06-05-08 Coding Table

Overview of 06-01 IO Flow

Summary

  • IO stream is used to process data transmission between devices
  • Java operates on data through streaming
  • Java objects for operation flow are all in the IO package

IO streams for memory devices

  • Input: Read data from peripherals into memory
  • Output: Write the number of memory into peripherals

IO flow classification

  • Flows are divided into two types according to operational data
    • Byte stream
    • Character stream
  • Flows are divided by direction of flow.
    • Input stream
    • output stream

06-02 Byte Stream and Character Stream Summary

06-02-01 character stream

IO system
- Top-level parent of byte stream
- InputStream
- FileInputStream
- BufferedInputStream
- OutputStream
- FileOutputStream
- BufferedOutputStream
- Top-level parent of character stream
- Reader
- FileReader
- BufferedReader
- InputStreamReader Conversion Stream
- Writer
- FileWirter
- BufferedWirter
- Output Stream Writer Conversion Stream

Character Stream Features: Only Words can be manipulated

Character stream origin: After the byte stream reads the text byte data, it does not directly operate, but first looks up the specified encoding table. Get the corresponding text, and then operate on the text.

Character stream = byte stream + encoding table

FileWirter class

Definition: Character output stream subclass whose object can write character data to a file

Be careful:
- This class does not have a null constructor because writing text data to a file must be explicit when creating an object
- If the file does not exist, create it automatically
- Auto-overwrite if the file already exists

Method
- wirte("Hello World!") writes data to the temporary storage buffer
- flush() refresh to store data from temporary storage buffer to destination
- close() closes the flow, closes resources, and calls flush to refresh the buffered data to the destination before closing

public class FileWriter {
    public static void main(String[] args) {
        //Create a character output stream object that can write character data to a file
        //Objects must be initialized when they are created
        FileWriter fw = new FileWriter("JAVA.txt", true);
        //Write data to temporary storage buffer
        fw.wirte("Hello World!");
        //Refresh to write data directly to the destination
        fw.flush();
        //Close the flow, close the resource, and call flush to refresh the data in the buffer to the destination before closing
        fw.close();
    }
}

details
- Line break: Create the variable private static final String LINE_SEPARATOR = null; line break
- Continuation: Write true in the construction method, which can be continued on the original document.
- new FileWirter("JAVA.txt",true)

IO exception handling

public class FileWriter {
    public static void main(String[] args) {

        FileWriter fw = null
        try {
            new FileWriter("JAVA.txt", );
            fw.wirte("Hello World!");
        } catch(IOException e) {
            System.out.println(e.toString());
        } finally {
            if(fw != null)
            try {
                fw.close();
            } catch(IOException e) {
                throw new RuntimeException("Shutdown failure");
            }
        }
    }
}

FileReader class

Definition: Character output stream subclass whose object can read a text file and print to the console

Be careful:
- This class does not have an empty constructor because the file must exist when it is read
- Actually, associating an existing file with a read stream
- Only one character can be read by a read

Method
- Read mode
- Read only one character at a time.
- Read mode 2 read(char []) read characters and store them in arrays
- close() closes the flow, closes resources, and calls flush to refresh the buffered data to the destination before closing

Reading mode 1

public class FileWriter {
    public static void main(String[] args) {
        //Create stream objects that read character data
        //Make sure that the document exists
        //Associate an existing file with a read stream
        FileReader fr = new FileReader("JAVA.txt");

        //Reading Characters by read Method in Reader
        int ch = fr.read();
        System.out.println(ch);
        //Duplicate read
        while((ch=fr.read())!= -1) {
            System.out.println((char)ch);
        }
        fr.close;
    }
}

Reading mode 2

public class FileWriter {
    public static void main(String[] args) {

        FileReader fr = new FileReader("JAVA.txt");
        //Create character arrays
        char[] buf = new char[3];
        //Store the read data in an array
        int num = fr.read(buf);
        System.out.println(new String(buf));
        //Duplicate read
        while((len=fr.read(buf)) != -1) {
            System.out.println(new String(buf,0,len ));
        }
    }
}

Reading and writing exercises
Copy a file to disk C

thinking

  • Read source data
  • Write the read data to the destination
  • Manipulating Text Data with Character Stream

Reproduction Mode 1

public class FileTest {
    public static void main(String[] args) throws IOExcepion {
        //Read text files
        FileReader fr = new FileReader("JAVA.txt");
        //Store text files
        FileWriter fw = new FileWirter("JAVA_COPY.txt");
        //Duplicate read
        int ch = 0;
        while((ch=fr.read()) != -1) {
            fw.wirte(ch);
        }
        fr.close();
        fw.close();
    }
}

Reproduction Mode II

public class FileTest {
    private static final int BUFFER_SIZE = 1024;
    public static void main(String[] args) throws IOExcepion {

        FileReader fr = null;
        FileWirter fw = null;
        try {
            fr = new FileReader("JAVA.txt");
            fw = new FileWirter(JAVA_COPY.txt);
            //Create a temporary container
            char[] buf = new char[BUFFER_SIZE];
            //Define the number of characters read by a variable record
            int len = 0while((len=fr.read(buf)) != -1)
                fw.wirte(buf, 0, len);
        } catch(Excepion e) {
            throw new RuntimeException("Failure to read and write");
        } finally {
            if(fw != null)
                try {
                    fw.close;
                } catch(IOException e) {
                    e.printStackTrace();
                }
            if(fw != null)
                try {
                    fr.close;
                } catch(IOException e) {
                    e.printStackTrace();
                }
        }
    }
}

Buffer

Improving IO Flow Operating Efficiency

  • BufferedReader
  • BufferedWirter

BufferWirter class

Constructor: Pass in a stream object to be buffered

common method

  • wirte: Write
  • newLine(): Line change
  • flush: refresh
  • close: Closed. After the buffer is closed, the buffered stream object is automatically closed.
public class BufferWirterDemo {
    public static void main(String[] args) {
        //Creating Write Stream Objects
        FileWriter fw = new FileWriter("buf.txt");
        //Create a buffer object for a character write stream
        //Buffer objects are associated with flow objects to be buffered
        BufferedWriter bufw = new BufferedWriter(fw);

        bufw.write("abc");
        bufw.newLine();//Line feed
        bufw.write("def");

        bufw.flush();
        bufw.close();
    }
}

BufferReader class

Constructor: Pass in a stream object to be buffered

common method

  • read(); read a character
  • readLine(): Read an entire line
    • Principle: The read method of reading buffer is used to buffer the read characters and judge the newline marker, and return the cached data before the marker.
public class BufferReaderDemo {
    public static void main(String[] args) {
        //Create read stream objects
        FileReader fr = new FileReader("buf.txt");
        //Create a buffer object for a character read stream
        //Buffer objects are associated with flow objects to be buffered
        BufferedReader bufr = new BufferedReader(fr);
        String line = null;
        while((line = bufr.readLine()) != null) {
            System.out.println(line);
        }
    }
}

Buffer Copy Files
One way

public class CopyDemo {
    public static void main(String[] args) {
        FileReader fr = new FileReader("buf.txt");
        BufferedReader bufr = new BufferedReader(fr);

        FileWriter fw = new FileWriter("buf_copy.txt");
        BufferedWirter bufw = new BufferedWirter(fw);

        inc ch = 0;
        while((ch=bufr.read())!=-1) {
            bufw.write(ch);
        }
        bufw.close();
        bufr.close();
    }
}

Mode two
Line by line replication

public class CopyDemo {
    public static void main(String[] args) {
        FileReader fr = new FileReader("buf.txt");
        BufferedReader bufr = new BufferedReader(fr);

        FileWriter fw = new FileWriter("buf_copy.txt");
        BufferedWirter bufw = new BufferedWirter(fw);

        String line = null;
        while((line=bufr.readLine())!= -1) {
            bufw.write(line);
        }
        bufw.close();
        bufr.close();
    }
}

Custom BufferReader

public class MyBufferReader {
    private FileReader r;
    //Buffer global array
    private char[] buf = new charp[1024];
    //Element pointers in operational arrays
    private int pos = 0;
    //Counter: Number of data in the record buffer
    MyBufferedReader(FileReader r) {
        this.r = r;
    }
    public int myRead() throws IOException {
        If(count == 0) {
            count = r.read(buf);
            pos = 0;
        }
        if(count < 0)
            return -1;
        char ch = buf[pos++];
        count--;
        return ch;
        /*
        if(count==0) {
            count = r.read(buf);
            if(count < 0) {
                return -1;
            }
            pos = 0;//Every time the data is fetched to the buffer, the corner label returns to zero.
            char ch = buf[pos];
            pos++;
            count--;
            return ch;
        } else if(count > 0) {
            char ch = buf[pos];
            pos++;
            count--;
            return ch;
        }
        */
    }
    public String myReadLine() {
        StringBuilder sb = new StringBuilder();
        int ch = 0;
        while((ch = myRead())!=-1) {
            if(ch == '\r') {
                continue;
            } else if(ch == '\n') {
                return sb.toString();
            } else {
                //Characters read from buffers are stored in buffers that cache row data
                sb.append((char)ch);
            }
        }
        return null;
    }
    public void myClose() {
        r.close();
    }
}

LineNumberReader class

Function: Readable rows

Method

  • setLineNumber(): Sets the number of starting rows
  • readLine(): Read the whole line
  • close(): close
public class LineNumberReaderDemo {
    public static void main(String[] args) {
        FileReader fr = new FileReader();
        LineNumberReader lnr = new LineNumberReader(fr);

        String line = null;
        //Set the number of starting rows
        lnr.setLineNumber(1);
        while((line=lnr.readLine())!=null) {
            System.out.println(lnr.getLineNumber()+":"+line);
        }
        lnr.close(0;)
    }
}

Decoration design pattern

Definition: Design patterns that enhance the functionality of a set of objects

Features: Decorative classes and decorated classes must belong to the same interface or parent class

Similarities and differences between decoration and inheritance

  • Similarity: Enhancement of object functionality can be achieved
  • Difference
    • Decoration is more flexible than inheritance

Embodiment of Decoration Flexibility

Traditional Inheritance and Expansion

Writer

  • TextWriter: Used to manipulate text
    • BufferedTextWriter
  • MediaWriter: Used to manipulate media
    • BufferedMediaWriter
  • WebWriter: Used to manipulate Web pages
    • BufferedWebWriter
  • Server Writer: Used to operate servers
    • BufferedServerWriter

Extension of Decoration Design

Writer

  • TextWriter: Used to manipulate text
  • MediaWriter: Used to manipulate media
  • WebWriter: Used to manipulate Web pages
  • Server Writer: Used to operate servers
  • BufferedWriter: Improving efficiency
public class PersonDemo {
    public static void main(String[] args) {
        Person p = new Person();
        EnhancedPerson p1 = new EnhancedPerson(p);
        p1.eat();
        EnhancedPerson2 p2 = new EnhancedPerson2();
        p2.eat();
    }
}
class Person {
    void eat() {
        System.out.println("Steak");
    }
}
//decorate
class EnhancedPerson {
    private Person p;
    EnhancedPerson(Person p) {
        this.p = p;
    }
    public void eat() {
        System.out.println("Appetizer");
        p.eat();
        System.out.println("Dessert");

    }
}
//inherit
class EnhancedPerson2 extends Person{
    public void eat() {
        System.out.println("Appetizer");
        super.eat();
        System.out.println("Dessert");
    }
}

06-02-02 byte stream

  • Top-level parent of byte stream
    • InputStream
      • FileInputStream
    • OutputStream
      • FileOutputStream

common method

  • FileInputStream
    • read();
    • available(); Gets byte length
  • FileOutputStream
    • write()

Basic demonstration of byte stream operation file

public class ByteStreamDemo {
    public static void main(String[] args) {
        demo_read();
        demo_write();
    }
    public static void demo_read() {
        //Create byte read stream objects and associate them with the specified file
        FileInputStream fis = new FileInputStream("bytedemo.txt");
        //Read one byte at a time
        int ch = fis.read();
        System.out.println((char)ch);
        //Complete reading
        int ch = 0;
        while((ch=fis.read())!=-1) {
            System.out.println((char)ch);
        }
        //Read with arrays
        byte[] buf = new byte[1024];
        int len = 0;
        while((len=fis.read(buf))!=0) {
            System.out.println(new String(buf,0,len));
        }
        //Read by available() method
        byte[] buf = new byte[fis.available()];
        fis.read(buf);
        System.out.println(new String(buf));
    }
    public static void demo_write() {
        //Create byte output stream objects to manipulate files
        FileOutputStream fos = new FileOutputStream("bytedemo.txt");
        //Write data directly to destination
        fos.write("abc".getBytes());
    }
}

Byte Stream Reading MP3 Exercise

public class CopyDemo {
    public static void main(String[] args) {
        copy_1();
        copy_2();
        copy_3();
    }
    //1024 bytes duplicated once
    public static void copy_1() throws IOException {
        FileInputStream fis = new FileInputStream("c:\\0.mp3");
        FileOutputStream fos = new FileOutputStream("c:\\1.mp3");
        byte[] buf = new byte[1024];
        int len = 0;
        while((buf=fis.read())!=0) {
            System.out.println(new String(buf,0,len));
        }
    }
    //Replication with Buffered
    public static void copy_2() throws IOException {
        FileInputStream fis = new FileInputStream("c:\\0.mp3");
        BufferedInputStream bufis = new BufferedInputStream(fis);
        FileOutputStream fos = new FileOutputStream("c:\\1.mp3");
        BufferedOutputStream bufos = new BufferedOutputStream(fos);

        int ch = 0;
        while((ch=bufis.read())!=-1) {
            bufos.write(ch);
            bufos.flush();
        }
        bufos.close();
        bufis.close();
    }
    public static void copy_3() throws IOException {
        FileInputStream fis = new FileInputStream("c:\\0.mp3");
        FileOutputStream fos = new FileOutputStream("c:\\1.mp3");
        byte[] buf = new byte[fis.available()];
        fis.read(buf);
        fos.write(buf);
        fos.close();
        fis.close();
    }
}

IO stream keyboard input

Keyboard Input Demo

public class ReadKey {
    public static void main(String[] args) throws IOException {
        readKey1();
        readKey2();
    }
    public static void readKey1() throws IOException {
        //Create input stream objects
        InputStream in = System.in;
        //Read the contents of the input stream object
        int ch = in.read();
        System.out.println(ch);
    }
    public static void readKey2() throws IOException {
        inputStream in = System.in;
        int ch = 0;
        while((ch=in.read()!=-1)) {
            System.out.println(ch);
        }
    }
}

Keyboard input converted to uppercase

Get the data entered by the user's keyboard and display it in capitals on the console. exit exits the input

thinking

  • Because keyboard input only reads one byte, to determine whether it is over, you need to spell the read byte into a string?
  • A container StringBuilder is needed to store strings
  • Change input data into string judgment before returning
public class ReadKey {
    public static void main(String[] args) throws IOException {
        readKey();
    }
    //Get the data entered by the user's keyboard and display it in capitals on the console. exit exits the input
    public static void readKey() throws IOException {
        //Create container
        StringBuilder sb = new StringBuilder();
        //Get the keyboard read stream
        inputStream in = System.in;
        //Define the bytes read by the variable record and obtain them in a loop
        int ch = 0;
        while((ch=in.read())!=-1) {
            if (ch=='\r')
                continue;
            if (ch=='\n') {
                String temp = sb.toString();
                    if("exit".equals(temp))
                        break;
                    System.out.println(temp.toUpperCase());
                    sb.delete(0,sb.length());
            } else {
                sb.append((char)ch);
            }
        }
    }
}

06-02-03 Conversion Flow

  • InputStreamReader
    • Byte Stream --> Character Stream
    • Bytes are decoded into characters
  • OutputStreamWriter
    • Character Stream --> Byte Stream
    • Character encoding into bytes

Effect

  • InputStreamReader: Decode byte streams into character streams so that they can use methods such as readLine().
  • Output Stream Writer: Encoding character streams into byte streams for output

Transformation relation

These two codes have the same function.
FileWriter: This is equivalent to the conversion stream using the default code table on the machine. It's a handy class.

InputStreamReader isr = new InputStreamReader(new FileInputStream("a.txt"),"GBK");  
FileReader fr = new FileReader("a.txt");
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("a.txt"))   
FileWriter fw = new FileWriter("a.txt");

Conversion stream for keyboard input to uppercase

Requirements: Keyboard input data displayed on the console

public class TransStreamDemo {
    public static void main(String[] args) throws IOException {
        /*
        Byte stream acquisition
        InputStream in = System.in; 
        Byte stream decoded into character stream
        InputStreamReader isr new InputStreamReader(in);
        Character Stream Decoration
        BufferedReader bufr = new BufferedReader(isr);
        */
        BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));

        /*
        Byte stream
        OutputStream out = System.out;
        Character stream encoding into byte stream
        OutputStreamWriter osw = new OutputStreamWriter(out);
        Character Stream Decoration
        BufferedWriter bufw = new BufferedWriter(osw);
        */
        BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(System.out));


        String line = null;
        while((line=bufr.readLine())!=null) {
            if("exit".equals(line))
                break;
            bufw.write(line.toUpperCase());
            bufw.newLine();
            bufw.flush();
        }
    }
}

Requirements: Keyboard input data written to a file

BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));

BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("a.txt"));

Requirements: Text file content is displayed on the console

BufferedReader bufr = new BufferedReader(new InputStreamReader(new FileInputStream("a.txt"));

BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(System.out);

Requirements: Text file content is written to another file (copy)

BufferedReader bufr = new BufferedReader(new InputStreamReader(new FileInputStream("a.txt"));

BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("b.txt"));

Transformation relation

InputStreamReader isr = new InputStreamReader(new FileInputStream("a.txt"),"GBK");  
FileReader fr = new FileReader("a.txt");
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("a.txt"))   
FileWriter fw = new FileWriter("a.txt");

These two codes have the same function.
FileWriter: This is equivalent to the conversion stream using the default code table on the machine. It's a handy class.
Conversion streams must be used if other encodings are to be used.

Write with UTF-8

OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("a.txt"), "UTF-8");

Reading with UTF-8

InputStreamReader isr = new InputStreamReader(new FileInputStream("a.txt"), "UTF-8");  

Conversion flow applications

  • The device corresponding to the source item is a byte stream, but the operation is really text data, so you can use transformation as a bridge.
  • Conversion streams must be used when coding tables are needed to manipulate text.

Operating Rules of 06-02-04 IO Flow

Four clear

  • Clear Source and Purpose (Sink)
    • source
      • InputStream byte stream
      • Reader character stream
    • objective
      • OutputStream byte stream
      • Writer character stream
  • Is explicit data plain text data?
    • source
      • It's plain text Reader.
      • Not plain text InputStream
    • objective
      • It's plain text Writer.
      • Not plain text OutputStream
  • Specific equipment
    • source
      • Hard Disk: File
      • Keyboard: System.in
      • Memory: Array
      • Network: Socket stream
    • objective
      • Hard Disk: File
      • Console: System.out
      • Memory: Array
      • Network: Socket stream
  • Need additional functionality
    • Need to be efficient (Buffer)
    • Whether conversion is required

Demand embodiment

Requirement 1: Copy a text file

  • To clarify the source and purpose
    • Source InputStream Reader
    • Aim Output Stream Writer
  • Is it plain text: Yes
    • Source: Reader
    • Purpose: Writer
  • Clear equipment
    • Source: Hard Disk File
      • FileReader fr = new FileReader("a.txt");
    • Purpose: Hard disk File
      • FileWriter fw = new FileWriter("b.txt");
  • Identify whether additional functionality is needed: need to be efficient
    • Source:
      • BufferedReader bufr = new BufferedReader(fr);
    • Objective:
      • BufferedWriter bufw = new BufferedWriter(fw);

Requirement 2 Keyboard input data and file

  • To clarify the source and purpose
    • Source InputStream Reader
    • Aim Output Stream Writer
  • Is it plain text: Yes
    • Source: Reader
    • Purpose: Writer
  • Clear equipment
    • Source: Keyboard System.in
      • InputStream in = System.in;
    • Purpose: Hard disk File
      • FileWriter fw = new FileWriter("b.txt");
  • Identify whether additional functionality is required:
    • Need transformation
      • Source:
        • InputStreamReader isr = new InputStreamReader(System.in);
      • Objective:
        • FileWriter fw = new FileWriter("b.txt");
    • High efficiency is needed.
      • Source:
        • BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
      • Objective:
        • BufferedWriter bufw = new BufferedWriter(new FileWriter("b.txt"));

Requirement 3 reads text files and displays them on the console

  • To clarify the source and purpose
    • Source InputStream Reader
    • Aim Output Stream Writer
  • Is it plain text: Yes
    • Source: Reader
    • Purpose: Writer
  • Clear equipment
    • Source: Hard Disk File
      • FileReader fr = new FileReader("a.txt");
    • OBJECTIVE: Console System.out
      • OutputStream out = System.out;
  • Identify whether additional functionality is required:
    • Need transformation
      • Source:
        • FileReader fr = new FileReader("a.txt");
      • Objective:
        • OutputStreamWriter osw = new OutputStreamWriter(System.out);
    • High efficiency is needed.
      • Source:
        • BufferedReader bufr = new BufferedReader(new FileReader("a.txt"));
      • Objective:
        • BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(System.out));

Requirement 4 Keyboard input data displayed on console

  • To clarify the source and purpose
    • Source InputStream Reader
    • Aim Output Stream Writer
  • Is it plain text: Yes
    • Source: Reader
    • Purpose: Writer
  • Clear equipment
    • Source: Console System.in
      • InputStream in = System.in;
    • OBJECTIVE: Console System.out
      • OutputStream out = System.out;
  • Make it clear whether additional functionality is needed: two bytes for a word in Chinese, so you need to convert it into a string operation
    • Need transformation
      • Source:
        • InputStreamReader isr = new InputStreamReader(System.in);
      • Objective:
        • OutputStreamWriter osw = new OutputStreamWriter(System.out);
    • High efficiency is needed.
      • Source:
        • BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
      • Objective:
        • BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(System.out));

06-03 File class

File class features

  • Used to encapsulate files or folders as objects
  • Facilitate the operation of attribute information of files and folders
  • File object can be used as a construction method of parameter transfer to flow

Construction method

  • Pass in a string file path
File file1 = new File("c:\\a.txt");
  • Pass in a string folder path, a file name
File file2 = new File("c:\\", "a.txt");
  • Input a file object, a file name
File f = new File("c:\\");
File file3 = new File(f, "a.txt");

Application of separators

File file4 = new File("c:"+File.separator+"abc"+File.separator+"a.txt");
public class FileDemo {
    public static void main(String[] args) {
        constructiorDemo();
    }
    public static void constructiorDemo() {
        //You can encapsulate an existing or non-existent file or directory as a file object
        File file1 = new File("c:\\a.txt");
        File file2 = new File("c:\\", "a.txt");
        File f = new File("c:\\");
        File file3 = new File(f, "a.txt");
        File file4 = new File("c:"+File.separator+"abc"+File.separator+"a.txt");
    }
}

common method

  • Obtain
    • Get the file name: getName()
    • Get the file path
      • Get the relative path: getAbsolutePath()
      • Get the absolute path: getPath()
    • Get the file size: getLength()
    • Get the file modification time: lastModified()
public static void getDemo() {
    File file = new File("a.txt");
    String name = file.getName(); a.txt

    String absPath = file.getAbsolutePath(); C:\abc\a.txt //Absolute path
    String path = file.getPath(); a.txt

    long len = file.length(); 123

    long time = file.lastModified(); 1236102144203
}
  • Create and delete
    • Create delete files
      • boolean createNewFile()
        • If the file does not exist, create
        • If the file exists, it is not created
      • boolean delete()
    • Create Delete Folder
      • Create a single-level directory
        • mkdir()
      • Create multilevel directories
        • mkdirs()
      • remove folders
        • boolean delete()
public static void createAndDeleteDemo() {
    File file = new File("file.txt");
    boolean a = file.createNewFile();
    System.out.println(a); true
    boolean b = file.delete();
    System.out.println(b); true
}
  • judge
    • Determine whether there is isDemo()
    • Determine whether the file isFile()?
    • Determine whether the folder is isDirectory()?
public static void isDemo() {
    File file = new File("aa.txt");
    boolean b = file.exists();
    System.out.println(b);true
}
  • rename
    • renameTo();
public static void isDemo() {
    File file1 = new File("aa.txt");
    File file2 = new File("bb.txt");
    file1.renameTo(file2);
}
  • Get the system root directory
    • listRoots();
public static void listRootsDemo() {
    File[] file1 = File.listRoots();
    for(File file : files) {
        System.out.println(file);
    }
}
  • Capacity acquisition
    • getFreeSpace() Gets free space
    • getTotalSpace() Gets the total space
    • getUsableSpace() Gets the used space
public static void getSpaceDemo() {
    File file = new File("d:\\");
    file.getFreeSpace();
    file.getTotalSpace();
    file.getUsableSpace();
}
  • Get directory
    • String list()
      • file must be a directory
      • Otherwise NullPointerException will occur
      • Accessing system-level directories also causes null pointer exceptions
      • If the directory has no content, it returns an array with a length of 0.
      • Returns the file and folder names
    • File listFiles()
      • Returns an array of file objects
public static void listDemo() {
    File file = new File("c:\\");
    String[] names = file.list();
    for(String name : names) {
        System.out.println(name);
    }
}
  • Filter

As long as the Java file

public static void listDemo2() {
    File dir = new File("c:\\");
    String[] names = dir.list(new FilterByJava());
    for(String name : names) {
        System.out.println(name);
    }
}
public class FilterByJava implements FilenameFilter {
    @Override
    public boolean accept(File dir, String name) {
        return name.endsWith(".java");
    }
}

Custom filter

public static void listDemo2() {
    File dir = new File("c:\\");
    String[] names = dir.list(new FilterByJava());
    for(String name : names) {
        System.out.println(name);
    }
}
public class SurffixFilter implements FilenameFilter {
    private String suffix;
    public SurffixFilter(String suffix) {
        super();
        this.suffix = suffix;
    }
    @Override
    public boolean accept(File dir, String name) {
        return name.endsWith(".java");
    }
}

depth-first traversal
List all files and directories

public class FileTest {
    public static void main(String[] aregs) {
        File dir = new File("e:\\demodir");
        listAll(dir);
    }
    public static void listAll(File dir) {
        System.out.println(getSpace(level)+dir.getName());
        level++;
        File[] files = dir.listFiles();
        for(int x = 0; x<files.length; x++) {
            if(files[x].idDirectory()) {
                listAll(files[x]);
            } else {
                System.out.println(getSpace(level)+files[x].getName());
            }
        }
    }
    private static String getSpace(int level) {
        StringBuilder sb = new StringBuilder;
        for(int x = 0; x<level; x++) {
            sb.append("     ");
        }
        return sb.toString();
    }
}

Delete all files and directories
Principle: delete from inside to outside

public class FileDeleteTest {
    public static void main(String[] aregs) {
        File dir = new File("e:\\demodir");
        removeDir(dir);
    }
    public static void removeDir(File dir) {
        File[] files = dir.listFiles();
        for(File file : files) {
            if(file.isDirectory()) {
                removeDir(file);
            } else {
                file.delete();
            }
        }
        dir.delete();
    }
}

06-03-01 Recursion

Definition: Method itself calls itself

Be careful:
- Recursive normalization must specify conditions, otherwise stack overflow is easy

Conversion to binary

public static void toBinary(int num) {
    if(num>0) {
        System.out.println(num%2);
        toBinary(num/2);
    }
0
1
1
}
public static void toBinary(int num) {
    if(num>0) {
        toBinary(num/2);
        System.out.println(num%2);
    }
1
1
0
}

Summation

public static int getSum(int num) {
    if(num == 1)
        return 1;
    return num+getSum(num-1);
}

Summation Stack Memory Graphics

int getNum(2 - 1) {
    if(1 == 1)
        return;                 1
    return 1 + getSum(1 - 1);
}
int getNum(3 - 1) {
    if(2 == 1)
        return;
    return 2 + getSum(2 - 1);   1+2
}
int getNum(4 - 1) {
    if(3 == 1)
        return;
    return 3 + getSum(3 - 1);   3+3
}
int getNum(5 - 1) {
    if(4 == 1)
        return;
    return 4 + getSum(4 - 1);   4+6
}
int getNum(5) {
    if(5 == 1)
        return;
    return 5 + getSum(5 - 1);   5+10
}

06-04 Properties Collection

basic function

  • Map
    • Hashtable
      • Properties
    • HashMap
    • TreeMap

Properties collection features:

  • Key and Value in a collection are both string types
  • The data in the collection can be saved into the stream and retrieved from the stream.

Properties collection action: Usually this collection is used to manipulate the configuration file that the key-value pair exists in form

  • One Access Function
    • setProperty
    • getProperty
public static void propertiesDemo() {
    //Create a Properties collection
    Properties prop = new Properties();
    //Storage elements
    prop setProperty("Kevin", 24);
    prop setProperty("Tony", 21);
    prop setProperty("Brian", 19);
    prop setProperty("Peter", 29);
    //Extract elements
    Set<String> names = prop.stringPropertyName();
    for(String name : names) {
        String value = prop.getProperty(name);
        System.out.println(name+":"+value);
    }
}
  • Two list method listing
public static void propertiesDemo() {
    //Create a Properties collection
    Properties prop = new Properties();
    //Storage elements
    prop setProperty("Kevin", 24);
    prop setProperty("Tony", 21);
    prop setProperty("Brian", 19);
    prop setProperty("Peter", 29);
    //List elements
    prop.list(System.out);
}
  • Three store s method storage
public static void propertiesDemo() {
    //Create a Properties collection
    Properties prop = new Properties();
    //Storage elements
    prop setProperty("Kevin", 24);
    prop setProperty("Tony", 21);
    prop setProperty("Brian", 19);
    prop setProperty("Peter", 29);
    //Store in a file
    FileOutputStream fos = new FileOutputStream("info.txt");
    prop.store(fos,"name+age");
    fos.close();
}
  • Four read files, output to console
public static void propertiesDemo() {
    //Create a collection
    Properties prop = new Properties();
    //File and input stream binding
    FileInputStream fis = new FileInputStream("info2.txt");
    //Load files into collections
    prop.load(fis);
    //Output set to console
    prop.list(System.out);
}
//Simulated load method
public static void myLoad() {
    Properties prop = new Properties();
    BufferedReader bufr = new BufferedReader(new FileReader("info.txt"));
    String line = null;
    while((line=bufr.readLine())!=null) {
        if(line.startsWith("#")) {
            continue;
        } else {
            String[] arr = line.split("=");
            prop.setProperty(arr[0], arr[1]);
        }
    }
    bufr.close();
}
  • Five modifications to existing configuration files

thinking

  • read file
  • Store Key and Value data in a file into a collection
  • Modifying Key and Value data through collections
  • File the modified data
public static void propertiesDemo() {
    //Files are encapsulated as objects
    File file = new File("info.txt");
    //Determine whether a file exists
    if(!file.exists()) {
        file.createNewFile();
    }

    //File read
    FileReader fr = new FileReader(file);
    //Creating Collection Storage Information
    Properties prop = new Properties();
    //Storing information in a stream into a collection
    prop.load(fr);
    //Modifying data
    prop.setProperties("Kevin", "24");
    //File and output stream binding
    FileWriter fw = new FileWriter(file);
    //Store modified data
    prop.store(fw,"");

    fw.close();
    fr.close();
}

Practice

Exercise 1: Get the number of times an application runs. If it runs more than five times, give a sign-up message that the number of times it has been used. And the end of operation

thinking
- Counter: Count every time the program starts
- The counter cannot be reset with the program closed, so it is stored on the hard disk.
Principle of counter
- When the program starts, read it first

public class PropertiesTest {
    public static void main (String[] args) {

    }
    public static void getAppCount() {
        File confile = new File("count.properties");
        if(!confile.exists()) {
            confile.createNewFile();
        }
        FileInputStream fis = new FileInputStream(confile);
        Properties prop = new Properties();
        prop.load(fis);

        //Number of times obtained from a collection through Key
        String value = prop.getProperty("time");
        //Define counters to record the number of times they are retrieved
        int count = 0;
        if(value!=null) {
            count = Integer.parseInt(value);
            if(count >= 5) {
                System.out.println("The number of usage has arrived");
            }
        }
        count++;
        //The changed number of times is restored to the collection
        prop.setProperty("time",count+"");

        FileOutputStream fos = new FileOutputStream(confile);
        fos.close();
        fis.close();
    }
}

Exercise 2: Create a list of files with extensions

Train of thought:

  • Deep traversal is required
  • To filter during traversal, store eligible content in containers
  • Traverse the contents of the container and write the absolute path to the file
public class Test {

    /**
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {

        File dir = new File("e:\\java0331");

        FilenameFilter filter = new FilenameFilter(){
            @Override
            public boolean accept(File dir, String name) {

                return name.endsWith(".java");
            }           
        };

        List<File> list = new ArrayList<File>();

        getFiles(dir,filter,list);

        File destFile = new File(dir,"javalist.txt");

        write2File(list,destFile);

    }
    /**
     * The contents of the specified directory are traversed in depth and filtered according to the specified filters.
     * Store filtered content in the specified container List.
     * @param dir
     * @param filter
     * @param list
     */
    public static void getFiles(File dir,FilenameFilter filter,List<File> list){

        File[] files = dir.listFiles();

        for(File file : files){
            if(file.isDirectory()){
                //Recursive!
                getFiles(file,filter,list);
            }else{
                //Filter the traversed files. The eligible File object is stored in the List collection. 
                if(filter.accept(dir, file.getName())){
                    list.add(file);
                }
            }
        }

    }

    public static void write2File(List<File> list,File destFile)throws IOException{

        BufferedWriter bufw = null;
        try {
            bufw = new BufferedWriter(new FileWriter(destFile));
            for(File file : list){
                bufw.write(file.getAbsolutePath());
                bufw.newLine();
                bufw.flush();
            }


        } /*catch(IOException e){

            throw new RuntimeException("Write failure ";
        }*/finally{
            if(bufw!=null)
                try {
                    bufw.close();
                } catch (IOException e) {

                    throw new RuntimeException("Shutdown failure");
                }
        }
    }

}

06-05 Other IO Classes

06-05-01 Print Stream

  • PrintStream bytes
  • PrintWriter character

Decorate other output streams. It adds functionality to other output streams so that they can easily print various data value representations.

PrintStream

Characteristic:

  • A print method is provided to print values of various data types and maintain the representation of data.
  • No IOException thrown

Construction method: can receive three types of values

  • String FileName
  • File object (File file)
  • Output Stream out

Method

  • write(97)
    • Output a: Write only the lowest 8 bits
  • print(97)
    • Output 97: Turn 97 into characters and print the data to the destination.
public class PrintDemo {
    public static void main(String[] args) {
        PrintStream out = new PrintStream("print.txt");
        out.write(97); a
        out.print(97); 97
    }
}

PrintWriter

Character Printing Stream

Construction method

  • String Path
  • File object
  • Byte Output Stream
  • Character Output Stream
public class PrintWriterDemo {
    public static void main(String[] args) {
        BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter out = new PrintWriter(System.out);
        String line = null;
        while((line = bufr.readLine())!=null) {
            if("over".equals(line))
                out.println(line.toUpperCase());
                out.flush();
        }
        out.close();
        bufr.close();
    }
}

06-05-02 Sequence Stream

SequenceInputStream

Function: Logically concatenate other input streams

Construction method

  • SequenceInputStream(InputStream s1, InputStream s2)

Inefficient synthesis of three files into one

public class SequenceInputStreamDemo {
    public static void main() {
        Vector<FileInputStream> v = new Vector<FileInputStream>)();

        v.add(new FileInputStream("1.txt"));
        v.add(new FileInputStream("2.txt"));
        v.add(new FileInputStream("3.txt"));

        Enumeration<FileInputStream> en = v.elements();

        SequenceInputStream sis = new SequenceInputStream(en);

        FileOutputStream fos = new FileOutputStream("4.txt");

        byte[] buf = new byte[1024];

        int len = 0;

        while((len=sis.read(buf))!=-1) {
            fos.write(buf,0,len);
        }
        fos.close();
        sis.close();
    }
}

Efficiently synthesize three files into one

public class SequenceInputStreamDemo {

    /**
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {


        /*
         * Requirement: Merge the data in the 1.txt 2.txt 3.txt file into one file.
         */

//      Vector<FileInputStream> v = new Vector<FileInputStream>();      
//      v.add(new FileInputStream("1.txt"));
//      v.add(new FileInputStream("2.txt"));
//      v.add(new FileInputStream("3.txt"));
//      Enumeration<FileInputStream> en = v.elements();

        ArrayList<FileInputStream> al = new ArrayList<FileInputStream>();
        for(int x=1; x<=3; x++){
            al.add(new FileInputStream(x+".txt"));
        }

        Enumeration<FileInputStream> en = Collections.enumeration(al);



        /*
        final Iterator<FileInputStream> it = al.iterator();
        Enumeration<FileInputStream> en = new Enumeration<FileInputStream>(){

            @Override
            public boolean hasMoreElements() {

                return it.hasNext();
            }

            @Override
            public FileInputStream nextElement() {

                return it.next();
            }

        };*/

        SequenceInputStream sis = new SequenceInputStream(en);

        FileOutputStream fos = new FileOutputStream("1234.txt");

        byte[] buf = new byte[1024];

        int len = 0;

        while((len=sis.read(buf))!=-1){
            fos.write(buf,0,len);
        }

        fos.close();
        sis.close();

    }

}

File Cutting and Merging

File cutting

  • Cut by the number of files
    • Cut into fixed equal parts
  • Cut by file size
    • Cut into fixed size
public class SplitFileDemo {
    private static final int SIZE = 1024*1024;
    public static void main(String[] args) {
        File file = new File("c:\\0.bmp");
        splitFile(file);
    }
    public static void splitFile(File file) {
        //Read Stream Associated Files
        FileInputStream fis = new FileInputStream(file);
        //Define a 1M buffer
        byte[] buf = new byte[SIZE];
        //Create purpose
        FileOutputStream fos = null;

        int len = 0;
        int count = 1;

        File dir = new File("c:\\partfiles");
        if(!dir.exists())
            dir.mkdirs();

        while((len=fis.read(buf))!=-1) {
            fos = new FileOutputStream(new File((count++)+".part"));
            fos.write(buf,0,len);
        }
        fos.close();
        fis.close();
    }
}

File merge

public class MergeFile {
    public static void static main(String[] args) {
        File dir = new File("c:\\partfiles");
        mergeFile(fir);
    }
}
public static void mergeFile(File dir) {
    ArrayList<FileInputStream> a1 = new ArrayList<FileInputStream>();

    for (int x = 1; x <= 3; x++) {
        a1.add(new FileInputStream(new File(dir, x+".part")));
    }

    SequenceInputStream sis = new SequenceInputStream(en);

    FileOutputStream fos = new FileOutputStream(new File(dir, "1.bmp"));

    byte[] buf = new byte[1024];

    int len = 0;
    while((len = fos.read(buf))!= -1) {
        fos.write(buf,0,len);
    }
    fos.close();
    sis.close();
}

File Cutting and Merging

public class SplitFileDemo {
    private static final int SIZE = 1024 * 1024;
    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        File file = new File("c:\\aa.mp3");
        splitFile_2(file);
    }
    private static void splitFile_2(File file) throws IOException {
        // Associate source files with read streams.
        FileInputStream fis = new FileInputStream(file);
        // Define a 1M buffer.
        byte[] buf = new byte[SIZE];
        // Create purpose.
        FileOutputStream fos = null;
        int len = 0;
        int count = 1;
        /*
         * When cutting a file, the name of the file to be cut and the number of fragmented files to be cut must be recorded. In order to facilitate merger.
         * This information is described by using key-value pairs. The properties object is used
         * 
         */
        Properties prop  = new Properties();

        File dir = new File("c:\\partfiles");
        if (!dir.exists())
            dir.mkdirs();
        while ((len = fis.read(buf)) != -1) {
            fos = new FileOutputStream(new File(dir, (count++) + ".part"));
            fos.write(buf, 0, len);
            fos.close();
        }
        //The information of the cut file is saved in the prop set.
        prop.setProperty("partcount", count+"");
        prop.setProperty("filename", file.getName());
        fos = new FileOutputStream(new File(dir,count+".properties"));
        //Store the data in the prop collection in a file. 
        prop.store(fos, "save file info");
        fos.close();
        fis.close();
    }
}
    public static void mergeFile_2(File dir) throws IOException {
        /*
         * Gets the configuration file object in the specified directory.
         */
        File[] files = dir.listFiles(new SuffixFilter(".properties"));
        if(files.length!=1)
            throw new RuntimeException(dir+",Not in this directory. properties Files with extensions or not unique");
        //Record configuration file objects.
        File confile = files[0];


        //Get the information in this file ================================================================.

        Properties prop = new Properties();
        FileInputStream fis = new FileInputStream(confile);

        prop.load(fis);

        String filename = prop.getProperty("filename");     
        int count = Integer.parseInt(prop.getProperty("partcount"));

        //Get all the fragmented files in this directory. =================================================================
        File[] partFiles = dir.listFiles(new SuffixFilter(".part"));

        if(partFiles.length!=(count-1)){
            throw new RuntimeException(" Fragmentation files do not meet the requirements, the number is not right!Should"+count+"individual");
        }
        //Associate fragmented files with stream objects and store them in collections. 
        ArrayList<FileInputStream> al = new ArrayList<FileInputStream>();
        for(int x=0; x<partFiles.length; x++){
            al.add(new FileInputStream(partFiles[x]));
        }
        //Merge multiple streams into a sequence stream. 
        Enumeration<FileInputStream> en = Collections.enumeration(al);
        SequenceInputStream sis = new SequenceInputStream(en);

        FileOutputStream fos = new FileOutputStream(new File(dir,filename));

        byte[] buf = new byte[1024];

        int len = 0;
        while((len=sis.read(buf))!=-1){
            fos.write(buf,0,len);
        }
        fos.close();
        sis.close();
    }

06-05-03 ObjectStream

ObjectStream

  • ObjectOutputStream
    • ObjectOutputStream writes basic data types and graphics of Java objects to hard disks by serialization
  • ObjectInputStream
    • ObjectInputStream can read objects by deserializing them

serialize

  • Objects are permanently stored on hard disk through serialization to achieve persistence

Deserialize

  • Reading Objects on Hard Disk into Memory by Deserialization

Be careful

  • Classes of serialized objects must implement Serializable interfaces
  • Serializable is a markup interface
  • General extension is. object
public class ObjectStreamDemo {
    public static void main(String[] args) throws IOException {
        writeObj();
        readObj();
    }
    public static void writeObj() throws IOException, ClassNotFoundException {
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("obj.object"));
        oos.writeObject(new Person("Steve", 30));
        oos.close();
    }
    public static void readObj() throws IOException {
        ObjectInputStream ois = new ObjectInputStream(new FileInpuStream("obj.object"));
        Person obj = (Person)ois.readObject();
        System.out.println(p.getName()+":"+p.getAge());
    }
}

Serializable interface

Role: Used to add ID numbers to serialized classes to determine whether classes and objects are the same version?

Note: If you do not customize the UID, the system will default to using the UID, but if the class of the serialized object is changed, the UID will be changed so that it cannot be deserialized.

Custom ID number

ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;

transient keyword transients modify non-static data and cannot be serialized

06-05-04 Random AccessFile class

Characteristic

  • This object can be read and written
  • The object maintains a byte array internally and manipulates elements in the array through pointers.
  • The position of the pointer can be obtained by the getFilePointer method, and the position of the pointer can be set by the seek method.
  • This object encapsulates byte output stream and input stream
  • The source and destination of the object can only be files.

Common methods:

  • Write in
    • If the file does not exist, create
    • If the file exists, do not create it
public class RandomAccessFileDemo {
    public static void main(String[] args) {
        writeFile();
    }
    //Write some personnel information using Random AccessFile object
    public static void writeFile() throws IOException {
        RandomAccessFile raf = new RandomAccessFile("ranacc.txt","rw");
        raf.write("Tony".getBytes());
        raf.write(97);
        raf.write("Steve".getBytes());
        raf.write(97);

        raf.close();
    }
    public static void readFile() throws IOException {
        RandomAccessFile raf = new RandomAccessFile("ranacc.txt","r");
        //Setting the pointer position by seek
        ref.seek(1*8);//Random reading, specify the location of the pointer can be

        byte[] buf = new byte[4];
        raf.read(buf);

        String name = new String(buf);
        int age = raf.readInt();

        System.out.println("name="+name);
        System.out.println("age="+age);

        raf.close();
    }
}

Random write
Setting Write Location with seek Method

public static void randomWrite() throws IOException {
        RandomAccessFile raf = new RandomAccessFile("ranacc.txt","r");
        //Write from the specified location
        raf.seek(3*8);//Start with the third eight
        raf.write("Steve".getBytes());
        raf.writeInt(102);

        raf.close();
    }

06-05-05 pipeline flow

PipedStream

  • PipedInputStream
  • PipedOutputStream
public class PipedStream {

    /**
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {

        PipedInputStream input = new PipedInputStream();
        PipedOutputStream output = new PipedOutputStream();

        input.connect(output);

        new Thread(new Input(input)).start();
        new Thread(new Output(output)).start();
    }
}
class Input implements Runnable{
    private PipedInputStream in;
    Input(PipedInputStream in){
        this.in = in;
    }
    public void run(){
        try {
            byte[] buf = new byte[1024];
            int len = in.read(buf);

            String s = new String(buf,0,len);

            System.out.println("s="+s);
            in.close();
        } catch (Exception e) {
            // TODO: handle exception
        }

    }
}
class Output implements Runnable{
    private PipedOutputStream out;
    Output(PipedOutputStream out){
        this.out = out;
    }
    public void run(){
        try {
            Thread.sleep(5000);
            out.write("hi,Here comes the pipe!".getBytes());
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
}

06-05-06 DataStream

Flow objects that operate on basic data types

public class DataSteamDemo {
    /**
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {
//      writeData();
        readData();

    }
    public static void readData() throws IOException {
        DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));

        String str = dis.readUTF();

        System.out.println(str);
    }
    public static void writeData() throws IOException {
        DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));

        dos.writeUTF("Hello");

        dos.close();
    }
}

Stream of 06-05-07 Operational Array

Operating the stream of byte arrays

  • ByteArrayStream
    • ByteArrayInputStream
    • ByteArrayOutputStream

Stream of Operating Character Array

  • CharArrayReader
  • CharArrayWriter

Operation string

  • StringReader
  • StreamWriter

ByteArrayStream

public class ByteArrayStreamDemo {
    /**
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) {
        ByteArrayInputStream bis = new ByteArrayInputStream("abcedf".getBytes());

        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        int ch = 0;

        while((ch=bis.read())!=-1){
            bos.write(ch);
        }
        System.out.println(bos.toString());
    }
}

06-05-08 Coding Table

Common coding tables

  • ASCII: American Standard Information Exchange Code
    • Represented in seven bits of a byte
  • ISO8859-1: European Code Table
    • Represented in 8 bits of a byte
  • GB2312: Chinese Coding Table in China
  • GBK: Chinese coding table in China, which combines more Chinese symbols
  • Unicode: International Standard Code Table
    • All words are represented in two bytes, and the Java language is Unicode.
  • UTF-8:8-bit Unicode Transformation Format uses up to three bytes to represent a character

Simple encoding and decoding

  • String -> byte array encoding
  • Byte Array --> String Decoding
public class EncodeDemo {
    public static void main(String[] args) {
        String str = "Hello";
        //Hello: GBK-60-29-70-61
        //Hello: UTF-8-28-67-96-27-91-67
        //Code
        byte[] buf = str.getBytes("utf-8");
        printBytes(buf);
        //Decode
        String s1 = new String(buf);
    }

    private static vodi printBytes(byte[] buf) {
        for(byte b : buf) {
            System.out.println(b);
        }
    }
}
public class EncodeDemo {
    public static void main(String[] args) throws IOException {
            /*
             * String - > byte array: encoding.
         * Byte Array - > String: Decode.
         * 
         * Hello: GBK: -60-29-70-61
         * 
         * Hello: utf-8: -28-67-96-27-91-67 
         * 
         * If you make up a mistake, you can't solve it.
         * If the edition is correct and the solution is wrong, it may be helpful.
         */
        String str = "Thank you";

        byte[] buf = str.getBytes("GBK");//Coding with GBK
        String s1 = new String(buf,"UTF-8");//Decoding with UTF-8
        System.out.println("s1="+s1);//Decoding failure, using special encoding to represent the original encoding
        byte[] buf2 = s1.getBytes("UTF-8");//Get the source byte.
        printBytes(buf2);

        String s2 = new String(buf2,"GBK");//Decoding with GBK
        System.out.println("s2="+s2);//It's possible to decode
//      encodeDemo(str);
    }
    /**
     * @param str
     * @throws UnsupportedEncodingException
     */
    public static void encodeDemo(String str)
            throws UnsupportedEncodingException {
        //Code;
        byte[] buf = str.getBytes("UTF-8");
//      printBytes(buf);
        //Decode:
        String s1 = new String(buf,"UTF-8");
        System.out.println("s1="+s1);
    }
    private static void printBytes(byte[] buf) {
        for(byte b : buf){
            System.out.print(b +" ");
        }
    }
}

Unicom problem
The UTF-8 of Unicom is the same as that of GBK, so the system that causes GBK coding will decode automatically with UTF-8, resulting in scrambling code.

public class LianTong {
    public static void main(String[] args) throws IOException {
    String str = "Unicom";
    /*
    11000001
    10101010
    11001101
    10101000
    */
    byte[] buf = str.getBytes("gbk");
    for(byte b :buf){
        System.out.println(Integer.toBinaryString(b&255));
    }
    }
}

Intercepting strings by bytes

In java, the string "abcd" is the same length as the string "abhello" and is four characters. But the corresponding number of bytes is different, one Chinese character occupies two bytes.
Define a method to fetch substrings according to the maximum number of bytes. For example: for "ab hello", if three bytes are taken, then the substring is half of the word "ab" and "you", then half of the word will be discarded. If four bytes are ab you, five bytes are ab you.

public class Test {
    /**
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {
        String str = "ab Hello cd Thank you";
//      STR = AB inkstone cd inkstone;
//      int len = str.getBytes("gbk").length;       
//      for(int x=0; x<len; x++){
//          System.out.println("intercept"+ (x+1)+ "byte result is:" +cutStringByte (str, x+1));
//      }
        int len = str.getBytes("utf-8").length;     
        for(int x=0; x<len; x++){
            System.out.println("Intercept"+(x+1)+"The result is:"+cutStringByU8Byte(str, x+1));
        }
//      String str = Yan;
//      byte[] buf = str.getBytes("gbk");
//      for(byte b : buf){
//          System.out.println(b);//-84  105 
//      }
    }
    /*

     */
    public static String cutStringByU8Byte(String str, int len) throws IOException {
        byte[] buf = str.getBytes("utf-8");
        int count = 0;
        for(int x=len-1; x>=0; x--){
            if(buf[x]<0)
                count++;
            else
                break;
        }
        if(count%3==0)
            return new String(buf,0,len,"utf-8");
        else if(count%3==1)
            return new String(buf,0,len-1,"utf-8");
        else 
            return new String(buf,0,len-2,"utf-8");

    }
    public static String cutStringByByte(String str,int len) throws IOException{

        byte[] buf = str.getBytes("gbk");

        int count = 0;
        for(int x=len-1; x>=0; x--){
            if(buf[x]<0)
                count++;
            else
                break;
        }
        if(count%2==0)
            return new String(buf,0,len,"gbk");
        else
            return new String(buf,0,len-1,"gbk");
    }
}

Posted by dough boy on Sun, 23 Dec 2018 13:33:06 -0800