I. Classification of streams

Sorted by input and output

  • Input stream: Reads data from a peripheral into memory.
  • Output stream: Writes data in memory to peripherals.

By byte, character classification

  • Byte stream: A stream of data transmitted in the basic unit of bytes during transmission.
  • Character stream: The stream of characters, the most basic unit of data transmitted during transmission.

Character streams

origin

The byte stream reads byte data, does not manipulate the data, but looks up the specified encoding table, and then operates on the text. Simply put, character stream = byte stream + encoding table.

A character stream that manipulates text

Write data to a file

FileWriter

Main construction methods:

  • New FileWriter(String Path) : If the file does not exist, it will be created automatically. If, the file already exists, the file will be overwritten. The same below.
  • New FileWriter(String Path, Boolean append) : If append is true, data can be appended, same as below.
  • new FileWriter(File file)
  • new FileWriter(File file,boolean append)

Practical methods:

  • Write (String STR) : Writes the String STR to the buffer
  • Write (char []ch) : Writes the character array CH to the buffer
  • Write (char CH [],int start,int offset) : Writes the characters whose length is offset from start in the character array CH to the buffer
  • Write (int C) : Writes the character C to the buffer
  • Flush () : Flushes data from the buffer to disk
  • Close () : closes the stream and resources. Flush data before closing (close automatically calls flush)

Wrap:

  • Because newlines are different on different operating systems, they need to be adapted to the operating system. This problem has been solved for us in Java.
  • Separator: Final String line=System.getProperty(“line.separator”);

I/O exception handling:

  • Standard writing:
FileWriter fw = null;
        try {
            fw = new FileWriter("G:/xxx.txt".true);
            fw.write("Sparrow outside the window, talking on a telephone pole, when you say that, it's very summery."); } catch (IOException e) { System.out.println(e.getMessage()); } finally {// You can close resources only when the FW is not empty. Otherwise, the empty pointer is abnormalif(fw ! = null) { try { fw.close(); } catch (IOException e) { throw new RuntimeException("Old tie, resource shutdown failed!"); }}}Copy the code

Read data from a file

FileReader

Construction method:

  • new FileReader(String path)
  • new FileReader(File file)

Practical methods:

  • Int read() : returns the character read one at a time (int type); If -1 is returned, the end of the stream has been read.
  • Int read(char ch[]) : returns the number of characters read each time

Schematic diagram of the method:

  • int read(char ch[],int start,int len)
  • Close () : closes the resource.

Exercise (Copy and paste a text file)

  • Use FileReader to continuously read text from the source file and write characters (or arrays of characters) to another file using FileWriter.
  • Note: Chinese garbled characters may be generated during copying because of inconsistent encoding modes: The encoding mode of characters read by FileReader and characters written by FileWriter is based on the encoding mode of the operating system. However, the encoding mode of TXT text may be inconsistent with the preceding encoding mode, resulting in garbled characters.
  • Schematic diagram of text file replication:

  • Implementation code:
public void test01() {
        FileReader fr = null;
        FileWriter fw = null;
        try {
            fr = new FileReader("G:\\ system property.txt");
            fw = new FileWriter("F:\\ system property.txt".true);
            char ch[] = new char[1024];
            int len = -1;
            while((len = fr.read(ch)) ! = -1) { fw.write(ch, 0, len); fw.flush(); } } catch (IOException e) { e.printStackTrace(); } finally {if(fr ! = null) { try { fr.close(); } catch (IOException e) { throw new RuntimeException("Abnormal..."); }}if(fw ! = null) { try { fw.close(); } catch (IOException e) { throw new RuntimeException("Abnormal..."); }}}}Copy the code

The buffer

BufferedWriter

Construction method:

  • New BufferedWriter(Writer Writer) : When creating a BufferedWriter, the character output must be passed in, which is equivalent to passing in resources. The buffer size is the default.
  • New BufferedWriter(Writer Writer,int size) : Specifies the buffer size to be size.

Practical methods:

  • write(String str)
  • write(int c)
  • write(char ch[])
  • write(char ch[],int start,int len)
  • NewLine () : newLine.
  • Flush () : Flushes, preferably every time data is written using the buffered stream.
  • Close () : closes the resource. Note: When BufferedWriter is turned off, the incoming character output stream is also turned off

BufferedReader

Construction method:

  • New BufferedReader(Reader Reader) : Create a BufferedReader and pass it in. The buffer size is the default.
  • New BufferedReader(Reader Reader,int size) : specifies the buffer size to be size.

Practical methods:

  • int read()
  • Int read(char ch[]) : reads a character and stores it into an array.
  • Int read(char ch[],int start,int len).
  • String readlLine() : Reads a line of text and returns the String read, or null if it reaches the end of the stream.

Read () and readLine() methods

LineNumberReader

LineNumberReader is a BufferedReader subclass. LineNumberReader is a BufferedReader subclass. LineNumberReader is a BufferedReader subclass.

Construction method:

  • new LineNumberReader(Reader reader)

Practical methods:

  • String readLine()
  • read(char ch[])
  • read(char[],int start,int len)
  • Int getLineNumber() : Gets the current line of the read.
  • Void setLineNumber() : the default number of lines is 0. If you set the behavior n, you start reading from line n+1.

Custom buffer

The code is as follows:

Public class MyBufferedReader {private FileReader fr; private char ch[] = new char[10]; Private int pos = -1; Private int count = 0; Constructor public MyBufferedReader(FileReader fr) {this.fr = fr; } // CustomreadMethod //brreadPublic int myRead() throws IOException {// The number of elements in the buffer is 0if(this.count == 0) { pos = -1; Int len = fr.read(this.ch); int len = fr.read(this.ch);if (len == -1)
                return- 1; this.count = len; // Read a character from the buffer --this.count; // Reduce the number of characters in the buffer by onereturn (int) ch[++pos];
        } else{// Buffer has data --this.count;return(int) ch[++pos]; Public String myReadLine() throws IOException {StringBuffer sb = new StringBuffer(); int len = 0;while((len = this.myRead()) ! = -1) { char c = (char) len;if (c == '\r')
                continue; / / meet'\r'Continue to readif (c == '\n') // Directlyreturn// Because if it breaks out of the loop, there is no way to tell whether it is reading the loop at the end of the stream or using itbreakOut of the loopreturn sb.toString();
            sb.append(c);
        }
        returnnull; Throws IOException {fr.close();} public void close() throws IOException {fr.close(); }}Copy the code

Binding design mode

  • Introduction: Binding design mode is to make the class more powerful.
  • Implementation principle: – see the following code:
public class Person {

    public void eat() {
        System.out.println("What a meal!!);
    }
}

public class NewPerson {
    private Person p;

    public NewPerson(Person p) {
        this.p = p;
    }

    public void eat() {
        System.out.println("Soup before meals");
        p.eat();
        System.out.println("Dessert"); }}Copy the code
  • Differences between binding design mode and inheritance:
    • Ornament is more refined than inheritance

Character stream

FileInputStream

Construction method:

  • new FileInputStream(String path)
  • new FileInputStream(File file)

Practical methods:

  • Int read() : Reads one byte of data. A return of -1 indicates that the end of the stream was read.
  • Int read(byte b[]) : reads the length of the data into the array B, returns the number of bytes read, returns -1 to indicate that the end of the stream was read. The detailed process of reading data into array B is the same as above and will not be described here.
  • int read(byte b[],int off,int len)
  • Int available() : returns an estimate of the data that can be read from the file (returns the size in bytes); This method can define the size of a byte array when it is created, but cannot be used when the file is too large.

FileOutputStream

Construction method:

  • new FileOutputStream(String path)
  • new FileOutputStream(File file)
  • new FileOutputStream(String path,boolean flag)
  • new FileOutputStream(File file,boolean flag)

A practical method

  • void write(byte b[])
  • void write(byte b[],int off,int len)
  • Void write(int b) : Write a character (char), but int.

BufferedInputStream

Construction method:

  • new BufferedInputStream(InputStream fis)
  • new BufferedInputStream(InputStream fis, int size)

Practical methods:

  • int read()
  • int read(byte []b)
  • int read(byte []b,int off,int len)
  • close()

BufferedOutputStream

Construction method:

  • new BufferedOutputStream(OutputStream fos)
  • new BufferedOutputStream(OutputStream fos,int size)

Practical methods:

  • void write(byte []b)
  • void write(byte []b,int off,int len)
  • void write(int ch)

4. Transform the flow

explain

  • Unreadable: Data stored on a disk is “unreadable”, that is, stored in bytes.
  • Legible: Data stored in memory is “legible”, that is, stored as characters.

InputStreamReader

  • New InputStreamReader (InputStream in) :
  • New InputStreamReader(InputStream in,String charsetName) : You need to pass in an InputStream object and decode it using the current platform (operating system) decoding method.

OutputStreamWriter: Decodes using the specified decoding method.

  • To convert readable data into unreadable data is to encode a stream of characters into a stream of bytes.
  • New OutputStreamWriter(OutputStream Out) : You need to pass in an OutputStream object, encoded using the current platform (operating system) encoding.
  • New OutputStreamWriter(OutputStream out,String charsetName) : Encodes using the specified encoding.

Transformation flow schematic

To read text in a specified encoding

When this is the case, a conversion stream is needed because only the conversion stream can specify the codec format. GBK parses a Chinese character into two bytes, and UTF-8 parses a Chinese character into three bytes. So, if the encoding used to write text is not the same as the decoding used to read it, garbled characters (or maybe question marks?) will be read. . The code is as follows:

@test // Writes a string to a text file using the specified encoding method public voidtest03() throws IOException {
        OutputStreamWriter outputStreamWriter =
                new OutputStreamWriter(new FileOutputStream("G:\\ Conversion stream.txt"), "GBK");
        outputStreamWriter.write("Hello big brother!!"); outputStreamWriter.flush(); } @test // Reads a string from a text file using the specified decoding format public voidtest04() throws IOException {
        InputStreamReader inputStreamReader =
                new InputStreamReader(new FileInputStream("G:\\ Conversion stream.txt"), "UTF-8");
        char[] ch = new char[10];
        int len = -1;
        while ((len = inputStreamReader.read(ch)) != -1) {
            System.out.println(new String(ch, 0, len));
        }
    }
Copy the code

Fifth, the File

Construction method:

  • New File(String path) : Encapsulates the File(folder) into an object according to the path.
  • New File(String parentPath,String childPath) : Encapsulates the File(folder) as an object according to the path of two strings. The advantage of this is that you can fill in the path flexibly.
  • New File(File f,String path) : Encapsulates files (folders) into objects according to File object F and path.

Fields in File (final type) :

  • The default name delimiter associated with the system
    • File. The separator, the String type. On Windows it is “”, on Linux it is “/”.
    • File. SeparatorChar: Indicates the char type.
  • The path separator associated with the system
    • PathSeparator: This character is used to separate the names of files in a given sequence of files in the form of a list of paths. On UNIX systems, this field is:. On Microsoft Windows systems, it is. .
    • File. PathSeparatorChar: indicates the char type.

Common methods:

  • To obtain
    • File name: String getName()
    • File (folder) path
      • Relative path: String getPath(); GetPath takes whatever path is passed to the File constructor relative to the path of the project. Because if there is no disk in the path, it must be a relative path. Write disk is the absolute path.
      • Absolute path: String getAbsolutePath()
    • File size: long length(); Returns the size in bytes.
    • File (folder) lastModified: long lastModified(), returns the number of milliseconds since January 1, 1970.
    • System directory and its capacity
      • Static File [] listRoots() : Returns an array of files.
      • Long getFreeSpace() : Gets the free space of the directory (disk) and returns the number of bytes (type long).
      • Long getTotalSpace() : Gets the total space of the directory (disk) and returns the number of bytes (type long).
      • Long getUsableSpace() : Gets the space that the directory (disk) can be used by the VM, and returns the number of bytes (type long).
    • The name of the file or folder in the current folder
      • String [] list()
      • String [] list(FilenameFilter filter) : Pass a filter (filter by file name).
      • Note: File must encapsulate a folder (directory). If it encapsulates a File, null-pointer exceptions will be thrown.
    • Files in the current folder (folder)
      • File [] listFiles() : Gets files (folders) in a folder. Returns an array of files that can be used to manipulate files, not just get File names.
      • File [] listFiles(FilenameFilter filter) : Pass a filter (filtered by Filename).
      • File [] listFiles(FileFilter filter) : Pass a filter (filter by File).
    • Filter interpretation
      • There are two types of filters, one is FilenameFilter (filter by file name, for example, filter out files with a non-.txt suffix), and the other is FileFilter (filter by file, for example, filter out hidden files).
      • FilenameFilter: FilenameFilter is an interface that contains an abstract Boolean Accept (File f,String name) method that filters files. When a custom filter implements this interface, it implements the Accept () method, which leaves the currently traversed file if it returns true, otherwise it does not.
      • FileFilter: The principle of FileFilter filter is the same as the principle of FilenameFilter, but the abstract method in this interface is Boolean Accept (File f), the method argument is only a File object, no Filename. Because this filter is filtered by File, it is independent of the File name.
      • Filter schematic
  • Create and Delete
    • file
      • Create: Boolean createNewFile(); Creates a file based on the file’s path, if the file exists, do not create and return false; Otherwise create and return true. The following is the same, experience. (Unlike the IO stream side, which is directly overwritten every time).
      • Delete: Boolean delete(); Delete the file. Return true for successful deletion, false for failed deletion. The following is the same, experience. If a File has contents, such as File f=new File(“G:/a”), and a File has other files or folders, then f.dele () will fail. Windows deletes files from the inside out.
    • file
      • Create:
        • Boolean mkdir() : Create a single folder, for example, create only one A folder.
        • Boolean mkdirs() : Create multilevel folders, such as A /b/c/d/e/f.
      • Delete: Boolean delete(); Delete the file. If File f=new File(“G:/a/b/c/d/e/f”), then f.dele () will delete the f folder.
  • judge
    • Boolean exists() : Checks whether a file (folder) exists. Returns true if it does, false otherwise.
    • Boolean isFile() : Checks whether it is a file.
    • Boolean isHidden() : Checks whether files (folders) are hidden.
    • Boolean isDirectory() : Check whether it is a folder.
    • Boolean canRead() : Checks whether the file (folder) is readable.
    • Boolean canWrite() : Checks whether the file (folder) is writable.
    • Boolean canExecute() : Checks whether the file (folder) is runnable.
  • rename
    • Boolean renameTo(File des) : If the source File SRC and the destination File des are on the same disk, src.renameTo(des) will rename SRC with the name of DES. If SRC and des are not on the same disk, src.renameTo(des) cuts the SRC file to the disk where DES is located and renames SRC after DES.