Java I/O operations

This is my second article on getting started

This article describes common I/O operations in Java

The File type

The object of the File class is mainly used to obtain some information about the File itself, such as the directory where the File resides, the length of the File, and the read and write permission of the File

This paper mainly introduces the common methods of File class:

  • Construction method:

        File(String path)
        File(String parent, String child)
        File(File parent, String child)
        File(URI uri)
    Copy the code
  • Judging function

        boolean exists(a)
        boolean isAbsolute(a)
        boolean isDirectory(a)
        boolean isFile(a)
        boolean isHidden(a)
        boolean canRead(a)
        boolean canWrite(a)
        boolean canExecute(a)
    Copy the code
  • Create and Delete

        boolean createNewFile(a)
        boolean mkdir(a)
        boolean mkdirs(a)
        boolean delete(a)
    Copy the code
  • Get file attributes

        long file.length()
        long file.getFreeSpace()
        long file.getTotalSpace()
        long file.getUsableSpace()
    
        File getAbsoluteFile(a);
        String getAbsolutePath(a);
        String getParent(a);
        File getParentFile(a);
        String getName(a);
        String getPath(a);
        long lastModified(a);
    Copy the code
  • Gets the file name and folder in the directory

        // Returns an array of strings containing the file name and directory name of the current abstract path
    	String[] list() 
        // Returns an array of files and directories under the name of the current abstract path
        File[] listFiles()
    // Lists the drive letters
        static File[] listRoots()
    Copy the code

I/O flow classification

There are more than 40 classes involved in the IO flow, but they are all derived from the following four abstract classes

  • **InputStream/Reader: ** The parent of all input streams, which are byte input streams and character input streams
  • **OutputStream/Writer: ** The parent of all output streams, which are byte output streams and character output streams

Because there are sometimes Chinese characters and other characters in the file, these characters will be processed by different character sets will be different bytes, if the use of byte stream to read will produce errors and inconvenience, so to use this kind of character class to read character files

Classification by operation mode is shown below

The following figure shows the classification of operation objects


File operations

Java provides a series of streams for file reading and writing operations, including FileInputStream, FileOutputStream, FileReader, and FileWriter

  • FileInputStream

    /** * the String constructor internally calls the File constructor */
        public FileInputStream(File file) throws FileNotFoundException
        public FileInputStream(String name) throws FileNotFoundException
        
    /** * common API */
    	// Reading a byte from the input stream returns an int, or -1 if the end of the file is reached
    	public int read(a) throws IOException
    	// Read up to b.length bytes from the input stream into the byte array, returning the total number of bytes read into the buffer, or -1 if the end of the file is reached
    	public int read(byte b[]) throws IOException
    	// Reads up to len bytes from the input stream into a byte array, storing bytes starting at the off position and returning the total number of bytes read into the buffer, or -1 if the end of the file is reached
    	public int read(byte b[], int off, int len) throws IOException
    
    	/ / close the flow
    	public void close(a) throws IOException
    Copy the code
  • FileOutputStream

    /** * Constructor * Throws FileNotFoundException */ if the file exists but is a directory or if the file does not exist and cannot be created
        public FileOutputStream(File file) throws FileNotFoundException
        public FileOutputStream(String name) throws FileNotFoundException
    	// If the append argument is true, bytes are written from the end of the file, otherwise the content is overwritten.
    	public FileOutputStream(File file, boolean append) throws FileNotFoundException
        
    /** * common API */
        public void write(int b) throws IOException
        public void write(byte b[]) throws IOException
        public void write(byte b[], int off, int len) throws IOException
        
    	/ / close the flow
        public void close(a) throws IOException
    Copy the code
  • FileReader

    • FileReaderInherited fromInputStreamReader.InputStreamReaderAll methods in theStreamDecoderMethods of a class
    The FileInputStream object calls the parent class constructor */
    	public FileReader(String fileName) throws FileNotFoundException
        public FileReader(File file) throws FileNotFoundException
            
    /** * Common API * InputStreamReader method */
        public int read(a) throws IOException
        // The cbuf array is the target array
        public int read(char[] cbuf) throws IOException
        public int read(char[] cbuf, int off, int len) throws IOException
    Copy the code
  • FileWriter

    • FileWriterInherited fromOutputStreamReader.OutputStreamReaderAll methods in theStreamEncoderMethods of a class
    /** * constructor */
    	public FileWriter(File file)
    	public FileWriter(String name)
    	public FileWriter(File file, boolean append)
    	public FileWriter(String name, boolean append) 
    
    /** * common API */
    	public void write(String str) throws IOException
    	/ / ASCII
    	public void write(int c) throws IOException
        public void write(char[] cbuf) throws IOException
        public void write(String str, int off, int len) throws IOException
        public void write(char[] cbuf, int off, int len) throws IOException
    Copy the code

The buffer action

Buffered streams are enhancements to the four basic byte streams and are built on top of them.

The basic principle of buffer flow is that an array of buffers with a default size is created when objects are created to reduce I/O times (accessing disk resources) and improve read/write efficiency

  • Byte buffer stream

    • BufferedInputStream

      /** * constructor */
      	public BufferedInputStream(InputStream in)
          public BufferedInputStream(InputStream in, int size)
              
      /** * common API, basically from the parent class */
      	// Reading a byte from the input stream returns an int, or -1 if the end of the file is reached
      	public int read(a) throws IOException
      	// Read up to b.length bytes from the input stream into the byte array, returning the total number of bytes read into the buffer, or -1 if the end of the file is reached
      	public int read(byte b[]) throws IOException
      	// Reads up to len bytes from the input stream into a byte array, storing bytes starting at the off position and returning the total number of bytes read into the buffer, or -1 if the end of the file is reached
      	public int read(byte b[], int off, int len) throws IOException
      	
      Copy the code
    • BufferedOutputStream

      /** * constructor */
      	public BufferedOutputStream(OutputStream out)
      	public BufferedOutputStream(OutputStream out, int size)
      
      /** * common API, basically from the parent */
      	public void write(int b) throws IOException
          public void write(byte b[]) throws IOException
          public void write(byte b[], int off, int len) throws IOException
      	// Force out the data in the buffer
      	public void flush(a) throws IOException
      	// Close output to release resources and write out the buffer's data
      	public void close(a) throws IOException
      Copy the code
  • Character buffer stream

    • BufferedWriter

      /** * constructor */
      	public BufferedWriter(Writer out)
      	public BufferedWriter(Writer out, int size)
              
      /** * common API, basically from the parent */
      	public void write(int c) throws IOException
          public void write(char[] cbuf) throws IOException
          public void write(String str, int off, int len) throws IOException
          public void write(char[] cbuf, int off, int len) throws IOException
          // Write a line separator (window: \r\n)
      	public void newLine(a) throws IOException
      Copy the code
    • BufferedReader

      /** * constructor */
       	public BufferedReader(Reader in)
      	public BufferedReader(Reader in, int sz)
      /** * common API, basically from the parent */
       	public int read(a) throws IOException
          public int read(char[] cbuf) throws IOException
          public int read(char[] cbuf, int off, int len) throws IOException
      	// Read a line
      	public String readLine(a) throws IOException
      Copy the code

Transformation flows

  • InputStreamReader

    • InputStreamReader is a bridge from byte stream to character stream: it reads bytes and decodes them into characters using the specified charset. The character set it uses can be specified by name, can be explicitly specified, or can accept the platform’s default character set.

      Each call to one of the read() methods of InputStreamReader may result in one or more bytes being read from the underlying byte input stream. In order for bytes to be efficiently converted to characters, more bytes can be read from the underlying stream than is needed to satisfy the current read operation.

      /** * InputStreamReader sets character set */
      	public InputStreamReader(InputStream in, String charsetName)
      Copy the code
  • OutputStreamWriter

    • OutputStreamWriter is a bridge stream of characters to a byte stream: characters written to it are encoded using the specified byte charset. The character set it uses can be specified by name, can be explicitly specified, or can accept the platform’s default character set.

      Each call to the write() method causes the coder converter to be called on the given character. The resulting bytes are accumulated in the buffer before being written to the underlying output stream. The size of this buffer can be specified, but by default it is mostly used for most purposes. Note that characters passed to the write() method are not buffered.

      /** * OutputStreamWriter set character set */
      	public OutputStreamWriter(OutputStream out, String charsetName)
      Copy the code

The serialization stream

Serialization and deserialization

  • Serialization: The process of converting Java objects into byte sequences.
  • Deserialization: The process of restoring a sequence of bytes to Java objects.

In Java, if an object wants to be serialized, it implements one of two interfaces:

  • Serializableinterface
  • Externalizableinterface

Object serialization has two main uses:

  • To permanently store an object’s byte sequence on hard disk, usually in a file; (Persistent object)
  • Transmits the byte sequence of an object over the network. (Network transfer object)
  • Serialization ObjectOutputStream

    /** * constructor */
    	public ObjectOutputStream(OutputStream out)
    
    /** * common API */
    	// Write the specified object to the ObjectOutputStream
    	public void writeObject(Object ob)
    Copy the code
  • Deserialize ObjectInputStream

    /** * constructor */
    	public ObjectInputStream(a)
    
    Copy the code

Printing flow

PrintStream adds functionality to another output stream, that is, the ability to easily print representations of various data values without throwing ioExceptions

  • PrintStream

    /** * constructor */
    	// Print the destination as file
    	public PrintStream(File file)
    	public PrintStream(String fileName)
    	// Print to the output stream out
    	public PrintStream(OutputStream out)
    	
    Note: The PrintStream class inherits from FileOutputStream. You can also use methods from the parent class such as write() * but the write method prints */ according to the encoding table
    	public void print(a);
    	public void println(a);
    
    Copy the code