Java encapsulates files and folders on a computer as a File class that developers can use to manipulate files.

The File type

A static variable

// Returns the system path separator
String pathSeparator = File.pathSeparator;  // Win environment is;

// Returns the system default name separator
String separator = File.separator;  // The Win environment is /
Copy the code

The other two are return string values.

A constructor

// You can pass an absolute or relative path to the file.
File(String pathname)
// Pass two parameters: the first parameter is the folder and the second parameter is the file name.
public File(String parent, String child)
Copy the code

Commonly used method

File file = new File(".. /test.txt");
// Returns the absolute path to the file
file.getAbsoluteFile();
// Return the path name
file.getPath();
// Returns the file name or directory name
file.getName();
Return the length of the file
file.length();
// Check whether the passed file or directory exists
file.exists();

// If the path does not exist, both methods return false
// Check whether the path is a directory
file.isDirectory();
// Check whether the path is a file
file.isFile();
// If the directory does not exist, create one
file.mkdir();

// Creating a file or directory may fail, which means an exception may be thrown, so exceptions must be handled
// If the file name does not exist, create one
file.createNewFile()
// Create recursively, as mkdir -p
file.mkdirs()

// If the path passed does not exist or is not a directory, a null pointer exception will be thrown
// Mandatory String Array, all subfiles or directories in the passed path
file.list()
// Returns an array of files representing all files or directories in the File directory
file.listFiles()
Copy the code

The filter

grammar

public class FileFilterImpl implements FileFilter{
	@Override
	public boolean accept(File pathname) {
		return false; }}Copy the code
  • The listFiles method traverses the passed directory, retrieving each File in the directory and encapsulating it as a File object.
  • The listFiles method calls the Accept method in the filter passed by the parameter.
  • The listFiles method passes each File object iterated through to the Accept method. Very similar to the filter in Vue2.

If Accept returns true, the passed File object is stored in the File array.

Use filters to find EJS files in directories

public class test{

    public static void main(String[] args) throws IOException {
        File file = new File("f:\\repos\\test");
        getAllFile(file);
    }


    public static void getAllFile(File dir){
        File[] files = dir.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                return pathname.isDirectory() || pathname.getName().toLowerCase().endsWith(".ejs"); }});// Use Lambda expression optimization
        // File[] files = dir.listFiles(pathname->pathname.isDirectory() || pathname.getName().toLowerCase().endsWith(".ejs"));

        for (File file : files) {
            if (file.isDirectory()){
                getAllFile(file);
            }else{ System.out.println(file); }}}}Copy the code

Another filter is the FilenameFilter, which works similarly. The accPET method passes two parameters, the path and the file name.

File[] files = dir.listFiles(new FileFilter() {
            @Override
            public boolean accept(File dir,String name) {
                return new File(dir,name).isDirectory() || name.getName().toLowerCase().endsWith(".ejs"); }});Copy the code

IO stream

Reading data from the hard disk to memory is input (read), while writing data from memory to the hard disk is output (write). Data is different, so streams are divided into substantial input streams and character input streams.

Byte output stream

A superclass — OutputStream — for all classes that output the byte stream. Abstract method:

// Close the output stream and release all system resources associated with the stream (flush is automatically called)
close()
// Refresh this output stream and force all buffered output subsections to be written out (writing content to text)
flush()
// Writes the specified subsection to the input stream
wirte()
Copy the code

Writes data in memory to a hard disk file — FileOutputStream.

// Pass path or File instance
// The second argument defaults to false, and each write overwrites the previous one. If true, multiple writes are appended.
FileOutputStream fileOutputStream = new FileOutputStream("f:\\test.txt".true);
// FileOutputStream fileOutputStream = new FileOutputStream(new File("f:\\test.txt"));

// Write can also be passed an integer, Java will convert to ASCII code
fileOutputStream.wirte("hello world".getBytes());
fileOutputStream.close();

// Enter a newline
// win: \r\n
// Linux: /n
// mac: /r
Copy the code

The entire process of writing data is as follows: Java program -> JVM -> OS -> OS calls the method of writing data -> write data to a file.

Subsection input stream

A superclass of all classes that input the byte stream — InputStream. Abstract method:

/ / read
read()
/ / close the flow
close
Copy the code

Read data from a file on hard disk into memory — FileInputStream.

FileInputStream fileInputStream = new FileInputStream("f:\\test.txt".true);
// FileInputStream fileInputStream = new FileInputStream(new File("f:\\test.txt"));

// Reads a subsection of the file and returns (the pointer moves backwards), or -1 if it reaches the end
// fileInputStream.read()
// It is obviously not possible to use read() all the time, so the file is usually read as follows:
int len = 0; // Receive the subsection read
while(len = fileInputStream.read() ! = -1){
	System.out.println(len)
}

// Read can be passed as a byte array, which reads as many bytes as the length of the array. It is usually defined as 1024 (1Kb) or an integer multiple of it
// The int returned is the number of valid subsections

// int len = fileInputStream.read(new byte[1024])

byte[] bytes = new byte[1024];
int len = 0;
while((len = fileInputStream.read(bytes) ! = -1)){
	System.out.println(new String(bytes,0,len));
}



fileInputStream.close()

Copy the code

Read the entire process as follows: Java program -> JVM -> OS -> OS calls to read data -> read files.

A problem occurred while byte stream was reading Chinese. Because each character of Chinese encoding is greater than 1 subsection.

Character input stream

The superclass — Reader for all classes that input the character stream. Abstract method:

// Reads a single character and returns
// To pass a subsection array, read multiple characters and store the characters in the array
read()
// Release resources
close()
Copy the code

Read data from hard drive into memory as characters – FileReader.

FileReader fr = new FileReader("f:\\test.txt");
char[] cs = new char[1024];
int len = 0;
while((len = fr.read(cs)) ! = -1){
    System.out.println(new String(cs,0,len));
}
Copy the code

Character output stream

Writer is the superclass of all classes that output character streams. Writes character data in memory to a file – FileWriter. If FileOutputStream is not close, data will be added to the file. However, if Writer does not use the close or flush methods, the data is only in the buffer. Common methods:

// The second argument is true to enable continuation
try(FileWriter fw = new FileWriter("f:\\test1.txt".true);){
            char[] cs = {'d'.'e'};
            
            // You can pass an integer (ASCII), an array of characters, or a string
            fw.write(97);
            fw.write("bc");
            fw.write(cs);
        }
Copy the code

Properties

The Properties class implements the Map and Hashtable collections. Represents a persistent set of properties. It can be saved in the stream or loaded from the stream. It is a unique set combined with an IO stream. Common methods:

// Write temporary data to disk persistently
store()
// Read files (key-value pairs) from the hard disk into the collection
load
Copy the code

Its key and value are both strings by default. Output:

Properties properties = new Properties(); Properties.setproperty (" test ", "111"); Properties.setproperty (" Test1 ", "111"); Properties.store (new FileWriter("f:\\test3.txt"),"");Copy the code

File:

Read:

Properties properties = new Properties();
properties.load(new FileReader("f:\\test3.txt"));
properties.forEach((k,v)->{
    System.out.println(k + ":" + v);
});
Copy the code

Buffer flow

Enhancements to the previous basic flow. Can be divided into:

  • Subsection buffer flow
  • Character buffer stream

An I/O from the code through the JVM to the OS to the file takes many steps. Several subsections/characters at a time and multiple subsections at a time go through that process. With buffered streams, an array is created as a buffer when an object is created. Read/write buffer reduces I/O count and improves read/write efficiency.

Subsection buffered stream output

BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("f:\\test.txt"));
bufferedOutputStream.write("Test buffer".getBytes());
bufferedOutputStream.close();
Copy the code

Subsection buffer stream input

Much like output streams, use BufferedReader. Multiple readLine methods in the common method return NULL if the next line cannot be read.

BufferedReader bufferedReader = new BufferedReader(new FileReader("f:\\test.txt"));
bufferedReader.read();
String line;
while((line = bufferedReader.readLine()) ! =null){
    System.out.println(line);
}
Copy the code

Transformation flows

Specifies the encoding mode for the stream. Output:

OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream("f:\\test2.txt"), "utf-8");
outputStreamWriter.write("Test");
outputStreamWriter.close();
Copy the code

Input:

InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream("f:\\test3.txt"), StandardCharsets.UTF_8);
int len = 0;
byte[] cs = null;
while((len = inputStreamReader.read()) ! = -1){
    System.out.printf(String.valueOf((char)len));
}
inputStreamReader.close();
Copy the code

The serialization stream

Classes that implement serialization and deserialization must implement the Serializabel interface. Properties decorated static cannot be serialized. If you do not want the property to be static, you can use transient. Transient allows attributes to be unserialized and not added to static sections.

serialization

Writing an object as a stream to a file for storage is also called object serialization.

ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("f:\\test2.txt"));
objectOutputStream.writeObject(new Test("test".11));
objectOutputStream.close();
Copy the code

deserialization

The deserialization of an object stored in a file is read as a stream. Deserialization fails if the class file is changed after serializing the object and throws an InvalidaClassException.

ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("f:\\person.txt"));
Object o = objectInputStream.readObject();
objectInputStream.close();
System.out.println(o);
Copy the code

Printing flow

Only responsible for data output, not responsible for reading. IOException will not be thrown.

PrintStream printStream = new PrintStream("f:\\te.txt");
printStream.write(97); // a, use the print method to print as is
printStream.close();

// The output position of the system can be changed using setOut, in which the print stream is passed
System.out.println("Console output");
PrintStream printStream = new PrintStream("f:\\te.txt");
System.setOut(printStream);
System.out.println("Output to print stream destination");
Copy the code