Description of File class and IO flow

Table of contents

1. File class description

(1) The construction method creates the file

(2) Create function

(3) Judgment and acquisition function of File class

 (4) File delete function

2. I/O flow description

(1). Classification

3. Write data by byte stream

(1) Description

(2) Three ways to write data in byte stream

(3) Realize newline and additional writing when writing

(4) Add finally to the exception handling to realize the release of resources

4. Byte stream read data

(1) Description

5. Byte buffer stream

6. Character stream

(1) Description

(2) 5 ways to write data in character stream

(3) Two ways to read data by character stream

(4) FileReader and FileWriter

(5) Character buffer stream

(6) The unique function of the character buffer stream


1. File class description

File: It is an abstract representation of file and directory pathnames.

(1) The construction method creates the file

Files and directories can be encapsulated into objects through File.
For File, what it encapsulates is not a real file, but just a path name. It may exist, or it may not exist. In the future, the content of this path will be converted into concrete existence through specific operations.

Example: 

package com.example.demo.file;

import java.io.File;
import java.io.InputStream;

/**
 * @Author linaibo
 * @Date 2023/2/19 9:03
 * @PackageName:com.example.demo.file
 * @ClassName: FileDemo1
 * @Version 1.0
 */
public class FileDemo1 {

    public static void main(String[] args) {
        File file1 = new File("D:\\13-Notepad3-代替记事本\\Readme.txt");
        System.out.println(file1);
        File file2 = new File("D:\\13-Notepad3-代替记事本", "Readme.txt");
        System.out.println(file2);
        File file = new File("D:\\13-Notepad3-代替记事本");
        File file3 = new File(file, "Readme.txt");
        System.out.println(file3);
    }
}

(2) Create function

File class creation function:

public boolean createNewFile(): When a file with this name does not exist, create a new empty file named by the abstract path name; if the file does not exist, create the file and return true; if the file exists, do not create the file , and returns false.

public boolean mkdir(): Create a directory named by this abstract pathname. If the directory does not exist, create the directory and return true; if the directory exists, do not create the file and return false.

public boolean mkdirs(): Create a directory named by this abstract path name. If the directory does not exist, create the directory and return true; if the directory exists, do not create the file and return false.

Example:

 Note: If you want to create a file, but call the method of creating a directory, a directory will be created. If you do not delete this directory, and then execute the method of creating a file, an error will be reported. Only after deleting the file can the file be created. This point needs to be noted.

(3) Judgment and acquisition function of File class

Example 1:

 Example 2:

package com.example.demo.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

/**
 * @Author linaibo
 * @Date 2023/2/21 11:53
 * @PackageName:com.example.demo.file
 * @ClassName: FileDemo2
 * @Version 1.0
 */
public class FileDemo2 {
    public static void main(String[] args) throws FileNotFoundException {
        File file1 = new File("D:\\13-Notepad3-代替记事本");
        System.out.println(file1);
        boolean directory = file1.isDirectory();
        System.out.println("isDirectory:" + directory);
        boolean file = file1.isFile();
        System.out.println("isFile:" + file);
        boolean exists = file1.exists();
        System.out.println("exists:" + exists);
        String absolutePath = file1.getAbsolutePath();
        System.out.println("getAbsolutePath:" + absolutePath);
        String path = file1.getPath();
        System.out.println("getPath:" + path);
        String name = file1.getName();
        System.out.println("getName:" + name);
        System.out.println("list" + "------");
        String[] list1 = file1.list();
        for (String str : list1) {
            System.out.println(str);
        }
        System.out.println("listFiles" + "*******");
        File[] files = file1.listFiles();
        for (File fi : files) {
            System.out.println(fi);
        }
    }
}

result:

D:\13-Notepad3-代替记事本
isDirectory:true
isFile:false
exists:true
getAbsolutePath:D:\13-Notepad3-代替记事本
getPath:D:\13-Notepad3-代替记事本
getName:13-Notepad3-代替记事本
list------
Docs
Favorites
grepWinLicense.txt
grepWinNP3.exe
License.txt
lng
minipath.exe
minipath.ini
Notepad3.exe
Notepad3.ini
Readme.txt
Themes
listFiles*******
D:\13-Notepad3-代替记事本\Docs
D:\13-Notepad3-代替记事本\Favorites
D:\13-Notepad3-代替记事本\grepWinLicense.txt
D:\13-Notepad3-代替记事本\grepWinNP3.exe
D:\13-Notepad3-代替记事本\License.txt
D:\13-Notepad3-代替记事本\lng
D:\13-Notepad3-代替记事本\minipath.exe
D:\13-Notepad3-代替记事本\minipath.ini
D:\13-Notepad3-代替记事本\Notepad3.exe
D:\13-Notepad3-代替记事本\Notepad3.ini
D:\13-Notepad3-代替记事本\Readme.txt
D:\13-Notepad3-代替记事本\Themes

 (4) File delete function

2. I/O flow description

(1). Classification

According to the flow of data

  • input stream: read data
  • output stream: write data

According to data type

  • byte stream: byte input stream, byte output stream
  • Character stream: character input stream, character output stream

Generally speaking, we say that the classification of IO streams is based on the type of data, so under what circumstances are these two streams used?
If the data is opened through the Notepad software that comes with Window, we can also understand the contents inside , use a character stream. Otherwise a byte stream is used. If you don't know which type of stream to use, use byte stream.

3. Write data by byte stream

(1) Description

OutputStream: This abstract class is the superclass of all classes representing output byte streams.

Its subclasses all end with outputStream.

FileOutputStream: The file output stream is used to write data to File. FileOutputStream(String name): Create a file output stream to write to the file with the specified name

Steps to write data using byte output stream:

Create a byte output stream object (call the system function to create a file, create a byte output stream object, and let the byte output stream object point to the file).

Call the write data method of the byte output stream object.
Release resources (closes this file output stream and frees any system resources associated with this stream).

write method:

    /**
     * Writes <code>b.length</code> bytes from the specified byte array
     * to this file output stream.
     *
     * @param      b   the data.
     * @exception  IOException  if an I/O error occurs.
     */
    public void write(byte b[]) throws IOException {
        writeBytes(b, 0, b.length, append);
    }

    /**
     * Writes <code>b.length</code> bytes from the specified byte array
     * to this file output stream.
     *
     * @param      b   the data.
     * @exception  IOException  if an I/O error occurs.
     */
    public void write(byte b[]) throws IOException {
        writeBytes(b, 0, b.length, append);
    }

    /**
     * Writes <code>len</code> bytes from the specified byte array
     * starting at offset <code>off</code> to this file output stream.
     *
     * @param      b     the data.
     * @param      off   the start offset in the data.
     * @param      len   the number of bytes to write.
     * @exception  IOException  if an I/O error occurs.
     */
    public void write(byte b[], int off, int len) throws IOException {
        writeBytes(b, off, len, append);
    }

The parameter in the first method is an ASCII code, for example, when the value is 97, the a displayed in the file.

In the second method, the parameter is a byte array, and the String.getBytes() method can be used to convert the string into a byte array.

The third method can realize writing out part of the content of the array, off is the actual position, set to 0, len is the length, representing how many bits to read.

Example:

package com.example.demo.file;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @Author linaibo
 * @Date 2023/2/21 12:00
 * @PackageName:com.example.demo.file
 * @ClassName: FileOutputStreamDemo1
 * @Version 1.0
 */
public class FileOutputStreamDemo1 {
    public static void main(String[] args) throws IOException {
        String path = "F:\\output";
        File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        }
        File file1 = new File(file, "out.txt");
        if (!file1.exists()) {
            file1.createNewFile();
        }
        FileOutputStream fileOutputStream = new FileOutputStream("F:\\output\\out.txt", true);
        try {
            fileOutputStream.write("你好".getBytes(StandardCharsets.UTF_8));
            fileOutputStream.write("\r\n".getBytes(StandardCharsets.UTF_8));
            fileOutputStream.write("世界".getBytes(StandardCharsets.UTF_8));
            fileOutputStream.write("\r\n".getBytes(StandardCharsets.UTF_8));
        } finally {
            if (fileOutputStream != null) {
                fileOutputStream.close();
            }
        }

    }
}

(2) Three ways to write data in byte stream

(3) Realize newline and additional writing when writing

Newline: window:\r\n linux:\n mac:\r

Append write:

public FileOutputStream(String name, boolean append)
creates a file output stream to write to the file with the specified name. If the second parameter is true, bytes will be written to the end of the file rather than the beginning.

Example:

(4) Add finally to the exception handling to realize the release of resources

 Before releasing, it is necessary to judge whether the stream is null. If it is null, it does not need to be closed to avoid null pointer exceptions. 

4. Byte stream read data

(1) Description

InputStream: This abstract class is the superclass of all classes that represent input byte streams.

Its subclasses all end with inputStream.

FilelnputStream: Get input bytes from a file in the file system.
FilelnputStream(String name): Creates a FilelnputStream by opening a connection to the actual file named by the pathname name in the filesystem.

Steps to read data using byte input stream:

  • Create a byte input stream object.
  • The read data method of the stream object with byte input.
  • Release resources.

read method:

    /**
     * Reads a byte of data from this input stream. This method blocks
     * if no input is yet available.
     *
     * @return     the next byte of data, or <code>-1</code> if the end of the
     *             file is reached.
     * @exception  IOException  if an I/O error occurs.
     */
    public int read() throws IOException {
        return read0();
    }


    /**
     * Reads up to <code>b.length</code> bytes of data from this input
     * stream into an array of bytes. This method blocks until some input
     * is available.
     *
     * @param      b   the buffer into which the data is read.
     * @return     the total number of bytes read into the buffer, or
     *             <code>-1</code> if there is no more data because the end of
     *             the file has been reached.
     * @exception  IOException  if an I/O error occurs.
     */
    public int read(byte b[]) throws IOException {
        return readBytes(b, 0, b.length);
    }



    /**
     * Reads up to <code>len</code> bytes of data from this input stream
     * into an array of bytes. If <code>len</code> is not zero, the method
     * blocks until some input is available; otherwise, no
     * bytes are read and <code>0</code> is returned.
     *
     * @param      b     the buffer into which the data is read.
     * @param      off   the start offset in the destination array <code>b</code>
     * @param      len   the maximum number of bytes read.
     * @return     the total number of bytes read into the buffer, or
     *             <code>-1</code> if there is no more data because the end of
     *             the file has been reached.
     * @exception  NullPointerException If <code>b</code> is <code>null</code>.
     * @exception  IndexOutOfBoundsException If <code>off</code> is negative,
     * <code>len</code> is negative, or <code>len</code> is greater than
     * <code>b.length - off</code>
     * @exception  IOException  if an I/O error occurs.
     */
    public int read(byte b[], int off, int len) throws IOException {
        return readBytes(b, off, len);
    }

illustrate:

The first method is used to read one by one.

The second method is to read into a byte array. 

The third method is to read to a certain part of the array.

Example of reading data one byte at a time:

package com.example.demo.file;

import java.io.FileInputStream;
import java.io.IOException;

/**
 * @Author linaibo
 * @Date 2023/2/21 12:21
 * @PackageName:com.example.demo.file
 * @ClassName: FileInputStreamDemo1
 * @Version 1.0
 */
public class FileInputStreamDemo1 {
    public static void main(String[] args) throws IOException {
        FileInputStream fi = new FileInputStream("F:\\output\\out.txt");
        int read;
        while ((read = fi.read()) != -1) {
            System.out.print(read);
        }
        fi.close();
    }
}

result:

228189160229165189131022818415023114914013102281891602291651891310228184150231149140131022818916022916518913102281841502311491401310

 If the read value is -1, it means that the file has been read.

Example of reading an array of bytes at a time:

package com.example.demo.file;

import java.io.FileInputStream;
import java.io.IOException;

/**
 * @Author linaibo
 * @Date 2023/2/21 12:33
 * @PackageName:com.example.demo.file
 * @ClassName: FileInputStreamDemo2
 * @Version 1.0
 */
public class FileInputStreamDemo2 {
    public static void main(String[] args) throws IOException {
        FileInputStream fi = new FileInputStream("F:\\output\\out.txt");
        int read;
        byte[] bytes = new byte[1024];
        while ((read = fi.read(bytes)) != -1) {
            System.out.println(new String(bytes,0,read));
        }
        fi.close();
    }
}

result:

你好
世界
你好
世界
你好
世界

 Example of byte stream copying pictures, documents, videos, music:

package com.example.demo.file;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @Author linaibo
 * @Date 2023/2/21 21:47
 * @PackageName:com.example.demo.file
 * @ClassName: CopyJpgDemo
 * @Version 1.0
 */
public class CopyJpgDemo {
    public static void main(String[] args) throws IOException {
        FileInputStream fi = new FileInputStream("D:\\Backup\\Documents\\My Pictures\\Saved Pictures\\图片1.png");
        FileOutputStream fo = new FileOutputStream("F:\\output\\图片1.png");
        int read;
        byte[] bytes = new byte[1024];
        while ((read = fi.read(bytes)) != -1) {
            fo.write(bytes, 0, read);
        }

        fi.close();
        fo.close();

        FileInputStream fi1 = new FileInputStream("D:\\Backup\\Documents\\My Music\\测试音乐.mp3");
        FileOutputStream fo1 = new FileOutputStream("F:\\output\\测试音乐.mp3");
        int num;
        byte[] bytes1 = new byte[1024];
        while ((num = fi1.read(bytes1)) != -1) {
            fo1.write(bytes1, 0, num);
        }

        fi1.close();
        fo1.close();


        FileInputStream fi2 = new FileInputStream("D:\\Backup\\Documents\\MuMu共享文件夹\\123.xlsx");
        FileOutputStream fo2 = new FileOutputStream("F:\\output\\123.xlsx");

        int num2;
        byte[] bytes2 = new byte[1024];
        while ((num2 = fi2.read(bytes2)) != -1) {
            fo2.write(bytes2, 0, num2);
        }

        fi2.close();
        fo2.close();

        FileInputStream fi3 = new FileInputStream("D:\\Backup\\Documents\\My Videos\\bilibili\\234.mp4");
        FileOutputStream fo3 = new FileOutputStream("F:\\output\\234.mp4");

        int num3;
        byte[] bytes3 = new byte[1024];
        while ((num3 = fi3.read(bytes3)) != -1) {
            fo3.write(bytes3,0,num3);
        }

        fi3.close();
        fo3.close();

    }

}

5. Byte buffer stream

Byte buffer stream:
BufferOutputStream: This class implements a buffered output stream. By setting up such an output stream, an application can write bytes to the underlying output stream without incurring a call to the underlying system for each byte written.
BuferedInputStream: Creating a BufferedInputStream will create an array of internal buffers that will be refilled as needed from the contained input stream, many bytes at a time, as bytes are read or skipped from the stream.

Construction method:
byte buffer output stream: BufferedOutputStream(OutputStream out)
byte buffer input stream: BufferedInputStream(lnputStreamin)

Why does the construction method need a byte stream instead of a specific file or path?
The byte buffer stream only provides a buffer, and the actual reading and writing of data depends on the basic byte stream object for operation.

package com.example.demo.file;

import java.io.*;

/**
 * @Author linaibo
 * @Date 2023/2/21 21:47
 * @PackageName:com.example.demo.file
 * @ClassName: CopyJpgDemo
 * @Version 1.0
 */
public class CopyJpgDemo {
    public static void main(String[] args) throws IOException {

        long start = System.currentTimeMillis();
        FileInputStream fi3 = new FileInputStream("D:\\Backup\\Documents\\My Videos\\bilibili\\234.mp4");
        FileOutputStream fo3 = new FileOutputStream("F:\\output\\234.mp4");

        int num3;
        byte[] bytes3 = new byte[1024];
        while ((num3 = fi3.read(bytes3)) != -1) {
            fo3.write(bytes3, 0, num3);
        }

        fi3.close();
        fo3.close();
        long end = System.currentTimeMillis();
        System.out.println("共耗时" + (end - start) + "毫秒");

        long start1 = System.currentTimeMillis();
        BufferedInputStream bi = new BufferedInputStream(new FileInputStream("D:\\Backup\\Documents\\My Videos\\bilibili\\234.mp4"));
        BufferedOutputStream bo = new BufferedOutputStream(new FileOutputStream("F:\\output\\2344.mp4"));
        int num4;
        byte[] bytes4 = new byte[1024];
        while ((num4 = bi.read(bytes4)) != -1) {
            bo.write(bytes4, 0, num4);
        }
        bi.close();
        bo.close();
        long end1 = System.currentTimeMillis();
        System.out.println("共耗时" + (end1 - start1) + "毫秒");

    }

}

result:

共耗时47毫秒
共耗时18毫秒

Using buffered streams can improve performance.

6. Character stream

(1) Description

Character stream abstract base class:
Reader: abstract class of character input stream

Writer: Abstract class for character output streams

Two classes related to encoding and decoding problems in character streams:

InputStreamReader

OutputStreamWriter

InputstreamReader: is a bridge from byte stream to character stream. It reads bytes and decodes them into characters using the specified encoding. The charset it uses can be specified by name, can be specified explicitly, or the platform's default charset can be accepted.
OutputStreamWriter: is a bridge from character stream to byte stream. Encodes the written characters into bytes using the specified encoding. The charset it uses can be specified by name, can be specified explicitly, or the platform's default charset can be accepted.

The construction method of the character output stream

 The construction method of the character input stream

Example:

(2) 5 ways to write data in character stream

Example:

package com.example.demo.file;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

/**
 * @Author linaibo
 * @Date 2023/2/25 9:53
 * @PackageName:com.example.demo.file
 * @ClassName: FileReaderDemo1
 * @Version 1.0
 */
public class FileReaderDemo1 {
    public static void main(String[] args) throws IOException {

        //一次写入一个字符
        OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream("F:\\output\\test.xlsx"));
        writer.write(97);
        writer.flush();
        writer.write("你好");
        writer.flush();
        writer.close();

        //一次写入一个字符数组
        OutputStreamWriter writer1 = new OutputStreamWriter(new FileOutputStream("F:\\output\\test2.xlsx"));
        char[] chars = {'1','2','3'};
        writer1.write(chars);
        writer1.flush();
        writer1.write(chars,1,2);
        writer1.close();

    }

}

flush(): Refreshes the stream and can continue to write data.

close(): Close the stream and release resources, but the stream will be refreshed before closing, and data cannot be written once it is closed.

(3) Two ways to read data by character stream

Example:

package com.example.demo.file;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @Author linaibo
 * @Date 2023/2/25 10:19
 * @PackageName:com.example.demo.file
 * @ClassName: FileWriterDemo1
 * @Version 1.0
 */
public class FileWriterDemo1 {
    public static void main(String[] args) throws IOException {
        //一次读取一个字符
        InputStreamReader reader = new InputStreamReader(new FileInputStream("F:\\output\\out.txt"));
        int num;
        while((num = reader.read()) != -1){
            System.out.print(num);
        }
        reader.close();
        //一次读取一个字符数组
        InputStreamReader reader2 = new InputStreamReader(new FileInputStream("F:\\output\\out.txt"));
        char[] chars = new char[1024];
        int num2;
        while((num2 = reader2.read(chars)) != -1){
            System.out.print(new String(chars,0, chars.length));
        }
        reader2.close();
    }
}

Example of copying files:

package com.example.demo.file;

import java.io.*;

/**
 * @Author linaibo
 * @Date 2023/2/25 10:31
 * @PackageName:com.example.demo.file
 * @ClassName: CopyFileDemo1
 * @Version 1.0
 */
public class CopyFileDemo1 {
    public static void main(String[] args) throws IOException {
        // 创建流
        InputStreamReader in = new InputStreamReader(new FileInputStream("F:\\output\\test.txt"));
        OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream("F:\\output\\test1.txt"));

        // 读取数据
        int num;
        char[] chars = new char[1024];
        while((num = in.read(chars)) != -1){
            out.write(chars,0, chars.length);
        }

        // 关闭流
        in.close();
        out.close();

    }
}

(4) FileReader and FileWriter

The name of the conversion stream is relatively long, and our common operations are implemented according to the local default encoding . Therefore, in order to simplify writing, the conversion stream provides a corresponding subclass. If you want to specify other encodings, you cannot use this class.

 FileReader: Convenience class for reading character files. The construction method is as follows:

FileWriter: Convenience class for writing character files. The construction method is as follows: 

 Example:

(5) Character buffer stream

BufferedWriter: Writes text to a character output stream, buffering characters to provide efficient writing of single characters, arrays, and strings, the buffer size can be specified, or the default size can be accepted. The default is large enough for most purposes.

BufferedReader: Reads text from a character input stream, buffers characters to provide efficient reading of characters, arrays and lines, the buffer size can be specified, or the default size can be used. The default is large enough for most purposes.

Construction method:

BufferedWriter(Writer out)

BufferedReader(Readerin)

Example of a character buffered output stream:

Example of character buffered input stream:

Character buffer stream copy file case:

(6) The unique function of the character buffer stream

BufferedWriter:
void newLine0: Write a line with the line separator , the line separator string is defined by the system property.
BufferedReader:
public String readLine(): Read a line of text. The result is a string containing the contents of the line, excluding any line termination characters , or null if the end of the stream has been reached.

Example 1:

package com.example.demo.file;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @Author linaibo
 * @Date 2023/2/25 10:57
 * @PackageName:com.example.demo.file
 * @ClassName: BufferWriterDemo1
 * @Version 1.0
 */
public class BufferWriterDemo1 {
    public static void main(String[] args) throws IOException {

        BufferedWriter bw = new BufferedWriter(new FileWriter("F:\\output\\test.txt"));
        for (int i = 0; i < 5; i++) {
            // 写入
            bw.write("abc");
            // 换行
            bw.newLine();
            // 刷新
            bw.flush();
        }

        // 关闭
        bw.close();

    }
}

 Example 2:

package com.example.demo.file;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

/**
 * @Author linaibo
 * @Date 2023/2/25 11:02
 * @PackageName:com.example.demo.file
 * @ClassName: BufferReaderDemo
 * @Version 1.0
 */
public class BufferReaderDemo {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader("F:\\output\\test.txt"));

        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
        br.close();
    }
}

 Example 3 (copy files):

package com.example.demo.file;

import java.io.*;

/**
 * @Author linaibo
 * @Date 2023/3/1 12:34
 * @PackageName:com.example.demo.file
 * @ClassName: BufferRwCopyDemo
 * @Version 1.0
 */
public class BufferRwCopyDemo {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new FileReader("F:\\output\\out.txt"));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("F:\\output\\123456.txt"));
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            bufferedWriter.write(line);
            bufferedWriter.newLine();
            bufferedWriter.flush();
        }
        bufferedReader.close();
        bufferedWriter.close();
    }

}

Guess you like

Origin blog.csdn.net/m0_72167535/article/details/129104574