Java IO Stream

17 minute read

Published:

Java basics – Java IO Stream

Java IO Stream

File class

The java.io.File class is an abstract representation of file and directory path names, mainly used for operations such as file and directory creation, search, and deletion

The File class has nothing to do with the operating system

Static member variables

  • static String pathSeparator: system-related path separator string

  • static char pathSeparatorChar: system-related path separator

    Path separator: windows(;), Linux(:)

  • static String separator: name separator string related to the system

  • static char separatorChar: name separator related to the system

    Name separator: windows(\), Linux(/)

note:

  • Absolute path: complete path
  • Relative path: simplified path (relative to the root directory of the current project)

Construction method

  • File(String pathname): Create a new File instance by converting a given pathname string into an abstract pathname

    The string can be a file or a folder

    The path can be absolute or relative

    The path may or may not exist

  • File(String parent, String child): Create a new File instance based on the parent path name string and the child path name string

  • File(File parent, String child): Create a new File instance based on the parent abstract path name and child path name string

Common methods

  1. How to get features

    • public String getAbsolutePath(): Get the absolute path

    • public String getPath(): Get the path name (the path passed in the constructor)

    • public String getName(): Get the file or directory name (the end of the path)

    • public Long length(): Get the file length

      Cannot get the size of the folder, return 0

      If the path does not exist, return 0

  2. How to judge the function

    • public boolean exists(): Determine whether the path exists
    • public boolean isDirectory(): Determine whether the path is a folder
    • public boolean isFile(): Determine whether the path is a file
  3. How to create delete function

    • public boolean createNewFile(): when the file does not exist, create a new file (you cannot create a folder, the file path must exist)
    • public boolean delete(): delete files or directories (the contents in the folder will not be deleted)
    • public boolean mkdir(): create a directory (only single-level folders can be created)
    • public boolean mkdirs(): create directories and non-existent parent directories (single-level or multi-level folders)
  4. Directory traversal

    • public String[] list(): Get a string array of all subfiles or directories in the directory

    • public File[] listFiles(): Get all the sub-files in the directory or the File array of the directory

      If the path does not exist or is not a directory, a null pointer exception will be thrown

  5. File traversal

    • public File[] listFiles(FileFilter filter)

      java.io.FileFilter interface: filter for abstract pathname (File object)

      Abstract method: The method boolean accept(File pathname) used to filter files, to test whether the specified abstract path name is included in a certain path name list

    • public File[] listFiles(FilenameFilter filter)

      java.io.FilenameFilter interface: used to filter file names

      Abstract method: the method boolean accept(File dir, String name) used to filter files to test whether the specified file is included in a file list

    Note: You need to write your own implementation class and override the accept method

Introduction to IO Stream

 Input streamOutput stream
Byte StreamByte Input Stream
InputStream
Byte Output Stream
OutputStream
Character streamCharacter input stream
Reader
Character output stream
Writer

Byte stream

Byte output stream

java.io.OutputStream is an abstract class, the super class of all byte output streams.

  • Common methods
    1. public void close(): close the output stream and release system resources
    2. public void flush(): flush the output stream and force any buffered byte stream to be output
    3. public void write(byte[] b): write byte array to output stream
    4. public void write(byte[] b, int off, int len): write len bytes from the specified byte array, and output to the output stream from offset off
    5. public abstract void write(int b): write the specified byte to this output stream
  • File byte output stream java.io.FileOutputStream inherits OutputStream and writes the data in the memory to the file

    Construction method:

    1. FileOutputStream(String name): Create a file output stream that writes data to a file with a specified name
    2. FileOutputStream(File file): Create a file output stream that writes data to the file represented by the specified File object

    Steps for usage

    1. Create a FileOutputStream object, pass the data write destination in the constructor
    2. Call the write method to write the data to the file
    3. Close the stream and release resources

    Append write:

    1. FileOutputStream(String name, boolean append)

    2. FileOutputStream(File file, boolean append)

      Note: append is true for append mode, false is for overwrite mode

Byte input stream

java.io.InputStream is an abstract class, the super class of all byte input streams.

  • Common methods
    1. int read(): read the next byte of data from the input stream
    2. int read(byte[] b): Read a certain number of bytes from the input stream and store them in the buffer array b
    3. void close(): Close this input stream and release all system resources associated with the stream
  • File byte input stream java.io.FileInputStream inherits InputStream and reads the data in the file into memory

    Construction method:

    1. FileInputStream(String name): Create a file input stream that reads data from a file with a specified name
    2. FileInputStream(File file): Create a file input stream that reads data from the file represented by the specified File object

    Steps for usage:

    1. Create a FileInputStream object and pass the read data source in the constructor
    2. Call the read method to read the file
    3. Close the stream and release resources

Character stream

When using byte stream to read Chinese files, the complete characters may not be displayed, because one Chinese will occupy multiple bytes.

GBK: 2 bytes

UTF-8: 3 bytes

Character input stream

java.io.Reader is an abstract class, the super class of all character input streams.

  • Common methods
    1. int read(): read a single character
    2. int read(char[] cbuf): read multiple characters and store them in a character array
    3. void close(): close this input stream and release all system resources associated with the stream
  • java.io.FileReader inherited InputStreamReader inherited Reader, which is a file character input stream, which reads files into memory in character mode

    Construction method:

    1. FileReader(String fileName): Create a file character input stream that reads data from a file with a specified name
    2. FileReader(File file): Create a file character input stream that reads data from the file represented by the specified File object

    Steps for usage:

    1. Create a FileReader object and pass the read data source in the constructor
    2. Call the read method to read the file
    3. Close the stream and release resources

Character output stream

java.io.Writer is an abstract class, the super class of all character output streams.

  • Common methods
    1. void write(int c): write a single character
    2. void write(char[] cbuf): write character array
    3. abstract void write(char[] buf, int off, int len): write a part of the character array, write len bytes, and start writing from offset off
    4. void write(String str): write a string
    5. void write(String str, int off, int len): write part of the string, write len bytes, and start writing from offset off
    6. void flush(): flush the stream buffer
    7. void close(): close this stream, but first refresh
  • java.io.FileWriter inherited OutputStreamWriter inherited Writer, is a file character output stream, writes character data in memory to the file

    Construction method:

    1. FileWriter(String fileName): Create a file character output stream that writes data to a file with a specified name
    2. FileWriter(File file): Create a file character output stream that writes data to the file represented by the specified File object

    Steps for usage:

    1. Create a FileWriter object and pass the destination of data writing in the constructor
    2. Call the write method to write the data into the memory buffer (character to byte process)
    3. Call the flush method to flush the data in the memory buffer to the file
    4. Release resources (the data in the memory buffer will be flushed to the file first)

    The difference between close and flush:

    1. flush: flush the buffer, the stream object can continue to be used
    2. close: flush the buffer first, then close the resource, the stream object cannot be used anymore

    Append write:

    1. FileWriter(String fileName, boolean append)

    2. FileWriter(File file, boolean append)

      Note: append is true for append mode, false is for overwrite mode

IO stream exception handling

try{
    Stream operation
}
catch(IOException e){
    Exception handling logic
}
finally{
    try
    {
        if(fw!=null)
    fw.close();//Close the stream object
    }
    catch(IOException e){
        ...
    }
}

After JDK1.7+, you can add parentheses and define variables. The scope is valid in the try, and the resources will be automatically released after the try, without finally

try(define variable; define variable;...){
    Code that may produce an exception
}
catch(IOException e){
    Exception handling logic
}

After JDK1.9+, variables can be defined in front of the try, and the parentheses after the try can directly introduce the variable name. After the try code is executed, the resources are released directly, without finally

A a=new A();
B b=new B();
try(a,b){
    Code that may produce an exception
}
catch (exception type variable name) {
    Exception handling logic
}

Property set

The java.util.Properties class represents a persistent set of properties (inherited from Hashtable), which can be saved in the stream or loaded in the stream. Each key and its value in the attribute list is a string, which is unique to the IO stream Combine collection.

  • Common methods:

    1. store(OutputStream out, String comments),store(Writer writer, String comments): write the temporary data in the collection to the file (note: if you use byte stream you cannot write Chinese, the second parameter means What is the purpose of the saved file? Chinese cannot be used)

      (1) Create a Property collection object and add data

      (2) Create a byte/character output stream object, and bind the destination to be output in the construction method

      (3) Use the store method to store the temporary data in the collection to a file

      (4) Release resources

    2. load(InputStream instream),load(Reader reader): read the data in the file into the collection (note: if you use byte stream, you cannot write Chinese)

      (1) Create a Property collection object

      (2) Use the load method to read the data in the file

      (3) Traverse the Properties collection

      note:

      (1) In the file storing key-value pairs, the default connector for keys and values can be =, space, (other symbols)

      (2) In the file storing key-value pairs, you can use # to comment, and the commented content will not be read

      (3) In the file storing key-value pairs, the keys and values are strings by default, so no quotation marks are needed

    Note: Properties is a two-column set, the keys and values are strings by default

    1. Object setProperty(String key, String value): store the key-value pair in the collection, the bottom call is put
    2. String getProperty(String key): Get value by key, equivalent to get method
    3. Set<String> stringPropertyNames(): Returns the key set of this property list, equivalent to the keySet method

Buffered stream

Buffered stream is used to enhance the basic IO stream

  • Byte buffered stream: BufferedInputStream, BufferedOutputStream
  • Character buffered stream: BufferedReader, BufferedWriter

Byte buffered stream

  • Byte buffered output stream BufferedOutputStream, inherited OutputStream

    Construction method:

    1. BufferedOutputStream(OutputStream out): Create a new byte buffered output stream to write data to the specified underlying output stream
    2. BufferedOutputStream(OutputStream out, int size): Create a new byte buffered output stream to write data with the specified buffer size to the specified underlying output stream

    Steps for usage:

    1. Create a FileOutputStream object and bind the output destination in the constructor
    2. Create a BufferedOutputStream object and pass the FileOutputStream object in the constructor
    3. Use the write method to write data into the buffer
    4. Use the flush method to flush the data in the buffer to the file
    5. Release resources (flush will be called first)
  • Byte buffered input stream BufferedInputStream, inherited InputStream

    Construction method:

    1. BufferedInputStream(InputStream in): Create a new byte buffered input stream
    2. BufferedInputStream(InputStream in, int size): Create a new byte buffered input stream with the specified buffer size

    Steps for usage:

    1. Create a FileInputStream object and bind the read data source in the constructor
    2. Create a BufferedInputStream object and pass the FileInputStream object in the constructor
    3. Use the read method to read the file
    4. Release resources

Character buffer stream

  • Character buffered output stream BufferedWriter, inherited Writer

    Construction method:

    1. BufferedWriter(Writer out): Create a character buffered output stream using the default size buffer
    2. BufferedWriter(Writer out, int size): Create a character buffered output stream using a given size buffer

    Unique member method:

    void newLine(): write a line separator, the corresponding line separator will be used according to the operating system

    Steps for usage:

    1. Create a FileWriter object and bind the output destination in the constructor
    2. Create a BufferedWriter object and pass the FileWriter object in the constructor
    3. Use the write method to write data into the buffer
    4. Use the flush method to flush the data in the buffer to the file
    5. Release resources (flush will be called first)
  • Character buffered input stream BufferedReader, inherited Reader

    Construction method:

    1. BufferedReader(Reader in): Create a character buffered input stream with a default size buffer
    2. BufferedReader(Reader in, int size): Create a character buffered input stream using a given size buffer

    Unique member method:

    String readLine(): read a line of data, and return a string containing the content of the line according to the termination symbol of the corresponding line according to the operating system, or return null if the end of the stream has been reached

    Steps for usage:

    1. Create a FileReader object and bind the read data source in the constructor
    2. Create a BufferedReader object and pass the FileReader object in the constructor
    3. Use the read/readLine method to read files
    4. Release resources

    Conversion stream

    Character encoding and character set

    1. Character encoding

      • Encoding: Character -> Byte
      • Decoding: byte -> character
      • Character encoding: the corresponding rules between natural language characters and binary numbers
    2. Character set (code table)

      Character set: a set of all characters supported by a system

      A character set must have a character encoding

Conversion stream

  1. OutputStreamWriter

    Inherited Writer, encoding

    Construction method:

    • OutputStreamWriter(OutputStream out): Create an OutputStreamWriter (UTF-8) using the default encoding
    • OutputStreamWriter(OutputStream out, String charsetName): Create an OutputStreamWriter using the specified encoding (not case sensitive)

    Steps for usage:

    • Create an OutputStreamWriter object, pass the byte output stream and the specified encoding table name in the constructor
    • Use the write method to convert characters into bytes and store them in the buffer
    • Use the flush method to flush the bytes in the buffer to the file
    • Release resources
  2. InputStreamReader

    Inherited Reader, decoding

    Construction method:

    • InputStreamReader(InputStream in): Create InputStreamReader (UTF-8) with default encoding
    • InputStreamReader(InputStream in, String charsetName): Create InputStreamReader with specified encoding (not case sensitive)

    Steps for usage:

    • Create an InputStreamReader object, pass the byte input stream and the specified encoding table name in the constructor
    • Use the read method to read files
    • Release resources

    Note: The name of the encoding table must be the same as the encoding of the actual file, otherwise it will be garbled

Serialization

ObjectOutputStream: the serialization stream of the object (the object is written to the file in a stream for storage) ObjectInputStream: the deserialization stream of the object (read the object stored in the file in the form of a stream)

Serialization Stream

ObjectOutputStream inherits OutputStream and is a serialized stream of objects

  • Construction method:

    ObjectOutputStream(OutputStream out): Create a serialized stream that writes the specified byte output stream

  • Unique member method:

    void writeObject(Object obj): write the specified object to ObjectOutputStream

  • Steps for usage:

    1. Create an ObjectOutputStream object, pass the byte output stream in the constructor
    2. Use the writeObject method to write the object to the file
    3. Free up resources
  • Note: NotSerializableException may be thrown during serialization and deserialization. The java.io.Serializable interface (marked interface) needs to be implemented to enable the serialization function

Deserialization Stream

ObjectInputStream inherits InputStream and is the deserialization stream of objects

  • Construction method:

    ObjectInputStream(InputStream in): Create a deserialized stream that writes the specified byte input stream

  • Unique member method:

    Object readObject(): From ObjectInputStreamRead object

  • Steps for usage:

    1. Create an ObjectInputStream object, pass the byte input stream in the constructor
    2. Use the readObject method to read the file where the object is saved
    3. Free up resources
    4. Use the read object
  • Note:
    1. NotSerializableException may be thrown during serialization and deserialization. The java.io.Serializable interface (marked interface) needs to be implemented to enable the serialization function
    2. The readObject method may throw ClassNotFoundException, which is thrown when the class file of the object does not exist
    3. After serialization, if the class is modified and then deserialized, InvalidClassException (serial number conflict) will be thrown. Solution: Define the static final long serialVersionUID field in the class
  • static keywords: static keywords

    Member variables modified by static cannot be serialized

    transient keyword: transient keyword

    Member variables modified by transient cannot be serialized

java.io.PrintStream is a print stream

  • Features:
    1. Only responsible for data output, not for data reading
    2. Never throw IOException
    3. There are special methods: print, println, can output any type of value
  • Construction method:

    1. PrintStream(File file): The output destination is a file
    2. PrintStream(OutputStream out): The output destination is a byte output stream
    3. PrintStream(String fileName): The output destination is a file path
  • Note:

    If you use the write method to write data, you will query the encoding table when viewing the data

    If you use the print and println methods to write data, the data will be output as it is

  • Common methods:

    static void setOut(PrintStream out): You can change the flow direction of the print stream, and use the System.setOut method to change the destination of the output statement