Catalog
Irregular recursive resolution file search
Common bottom composition of strings
Encoding and decoding operations for character sets
File byte input stream: FileInputStream
File byte output stream: FileOutputStream
try-catch-finally releases resources
File character input stream: FileReader
File character output stream: FileWriter
Scenarios applicable to byte and character streams
Video Tutorial Portal - > https://www.bilibili.com/video/BV1Cv411372m?p=149
Data stored in memory is used to process, modify, and manipulate
Files to keep data on disk for a long time
File class locates files and operation files - > IO stream reads and writes file data
File Class
File class File object (file, folder) representing the operating system under package java.io.File
File class function=>Locate file, get information about file itself, delete file, create file (cannot read and write file contents)
File Class Create Object
public File (String pathname) ->Create file objects from file paths
Absolute and relative paths
Absolute Path: Start with a drive letter File file1 = new File("D:\path");
Relative Path: Is Relative Engineering File file2 = new File("module name\path");
[Example]
package com.test.d1_file; import java.io.File; public class FileDemo { public static void main(String[] args) { //File creates objects that support absolute paths and relative paths File f1 = new File("D:\\resources\\pika.JPG"); // Absolute path System.out.println(f1.length()); File f2 = new File("file-io-app/src/data.txt"); System.out.println(f2.length()); } }
Output:
1717920
5
The file content of data.txt is Hello
Common API s for File Classes
1.File class's ability to determine file type and get file information
Public Boolean isDirectory () ->Test whether the File represented by this abstract path name is a folder
Public Boolean isFile () ->Test if the File represented by this abstract path name is a File
Public Boolean exists () ->Test if the File represented by this abstract path name exists
Public String getAbsolutePath () ->Returns the absolute path name string for this abstract path name
Public String getPath() ->Convert this abstract path name to a path name string
Public String getName() ->Returns the name of the file or folder represented by this abstract path name
Public long lastModified () ->Returns the last modified time value in milliseconds for the file
[Example]
package com.test.d1_file; import java.io.File; import java.text.SimpleDateFormat; public class FileDemo02 { public static void main(String[] args) { // 1. Absolute path creates a file object File f1 = new File("D:/resources/snowman.JPG"); // a. Get its absolute path. System.out.println(f1.getAbsolutePath()); //D:\resources\snowman.JPG // b. The path to use when getting the file definition. System.out.println(f1.getPath()); //D:\resources\snowman.JPG // c. Get the name of the file: with a suffix. System.out.println(f1.getName()); //snowman.JPG // d. Get the size of the file: number of bytes. System.out.println(f1.length()); // Byte size // e. Get the last modification time of the file long time = f1.lastModified(); System.out.println("Last modified:" + new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(time)); // f. Determine whether a file is a file or a folder System.out.println(f1.isFile()); // true System.out.println(f1.isDirectory()); // false } }
2.File Class Create File Function
Public Boolean createNewFile () ->Create a new empty file
Public Boolean MKDIR () ->Only one level folder can be created
Public Boolean MKDIR () -> can create multilevel folders
3.File Class Delete File Function
public boolean delete () ->Delete files or empty folders represented by this abstract path name
[Example] Create new or delete files
package com.test.d1_file; import java.io.File; import java.io.IOException; public class FileDemo03 { public static void main(String[] args) throws IOException { // a. Creating new files is almost unnecessary, since later files are created automatically f1 = new File("file-io-app\\src\\data02.txt"); System.out.println(f1.createNewFile()); // b.mkdir creates a first-level directory File f2 = new File("D:/resources/aaa"); System.out.println(f2.mkdir()); // c.mkdirs Create Multilevel Directory File f3 = new File("D:/resources/ccc/ddd/eee/ffff"); System.out.println(f3.mkdirs()); // d. Delete files or empty folders as you would occupy them System.out.println(f1.delete()); File f4 = new File("D:/resources/snowman.JPG"); System.out.println(f4.delete()); // // Only empty folders can be deleted, not non-empty folders File f5 = new File("D:/resources/aaa"); System.out.println(f5.delete()); } }
4. Traversal function of File class
Public String[] list () ->Gets all First-level File Names to a string array in the current directory
Public File[] listFiles () -> Gets all First-level File Objects in the current directory to an array of File Objects (common)
listFiles method considerations
Returns null when the caller does not exist
Returns null when the caller is a file
When the caller is an empty folder, an array of length 0 is returned
When the caller is a folder with content, returns an array of File s containing the path to all files and folders, including hidden content
Returns null when the caller is a folder that requires permission to enter
Walk through a folder level 1
package com.test.d1_file; import java.io.File; import java.util.Arrays; public class FileDemo04 { public static void main(String[] args) { // 1. Locate a directory File f1 = new File("D:/resources"); String[] names = f1.list(); for (String name : names) { System.out.println(name); } // 2. First-level file objects // Gets all the First-level File Objects in the current directory and returns them to an array of File Objects (Key) File[] files = f1.listFiles(); for (File f : files) { System.out.println(f.getAbsolutePath()); } // Note 3 File dir = new File("D:/resources/ccc/ddd/eee/ffff"); File[] files1 = dir.listFiles(); System.out.println(Arrays.toString(files1)); } }
Output:
ccc
pika.JPG
D:\resources\ccc
D:\resources\pika.JPG
[]
Irregular recursive resolution file search
listFile only searches for first-level file objects, which need to be done recursively
File search, from C:disk, search for a file name and output absolute path=>
The first level file object should be located
Traverse through all first-level file objects to determine if they are files
If it's a file, decide if it's what you want
If it's a folder, you need to continue recursively to repeat the process
[Example] Search for pika.JPG on disk D
package com.test.d2_recusion; import java.io.File; import java.io.IOException; /** Target: Go to D to determine the search eDiary.exe file */ public class RecursionDemo05 { public static void main(String[] args) { // 2. Incoming directory and file name searchFile(new File("D:/") , "pika.JPG"); } public static void searchFile(File dir,String fileName){ // 3. Determine if dir is a directory if(dir != null && dir.isDirectory()){ // Find it // 4. Extract the first-level file objects under the current directory File[] files = dir.listFiles(); // null [] // 5. Determine whether there is a first-level file object before it can be traversed if(files != null && files.length > 0) { for (File file : files) { // 6. Determine whether the current traversed level 1 file object is a file or a directory if(file.isFile()){ // 7. Is it what we are looking for, just output its path? if(file.getName().contains(fileName)){ System.out.println("Eureka:" + file.getAbsolutePath()); } }else { // 8. Is a folder and needs to continue searching recursively searchFile(file, fileName); } } } }else { System.out.println("Sorry, the location of the current search is not a folder!"); } } }
Output:
Found: D:\resources\pika.JPG
character set
Common bottom composition of strings
English and numbers account for one byte in any country's character set
Chinese characters account for 2 bytes in GBK characters
In UTF-8 encoding, a Chinese 1 usually takes up 3 bytes
Note: The character set before encoding and the well-coded character set must be consistent, otherwise Chinese character scrambling will occur (English and numbers will not be scrambled in any country's encoding).
Encoding and decoding operations for character sets
String Encoding Method
byte[] getBytes()
Encode the String as a series of bytes using the platform's default character set and store the result in a new byte array
byte[] getBytes(String charsetName)
Encodes the String as a series of bytes using the specified character set, and stores the result in a new byte array
String Decode Constructor
String(byte[] bytes)
Construct a new String by decoding the specified byte array with the platform's default character set
String(byte[] bytes, String charsetName)
Constructs a new String by decoding the specified byte array with the specified character set
Encoding and Decoding of Text
package com.test.d3_charset; import java.io.UnsupportedEncodingException; import java.util.Arrays; public class Test { public static void main(String[] args) throws Exception { // 1. Encoding: Convert text to bytes (using the specified encoding) String name = "Hello World HelloWorld"; //byte[] bytes = name.getBytes(); // Encoding with current code default character set (UTF-8) byte[] bytes = name.getBytes("GBK"); // Specify encoding System.out.println(bytes.length); System.out.println(Arrays.toString(bytes)); // 2. Decoding: Convert the bytes into their corresponding Chinese form (the character set before and after encoding must be the same, otherwise the bytes are scrambled) //String rs = new String(bytes); // Default UTF-8 String rs = new String(bytes, "GBK"); // Specify GBK decoding System.out.println(rs); } }
Notice that the encoding of Chinese characters is negative, and the output:
IO Stream
Role: Read and write file data
Classification of IO streams
In the direction of flow - > Base on memory
Input stream, data read from hard disk to memory
Output stream, data written out of memory to hard disk
By the smallest unit of data in the stream
Byte streaming operates on all types of files including audio, video, pictures, etc.
Character streams can only operate on plain text files, including java files, txt files, and so on
File byte input stream: FileInputStream
Read data from disk files into memory in bytes based on memory
constructor
public FileInputStream ->Create a byte input stream pipeline to connect to the source file object
public FileInputStream (String pathname) ->Same as above
Method Name
Public int read () ->Returns one byte at a time if the byte has no readable Return-1
Public int read (byte[] buffer) ->Return one byte array at a time if the byte has no readable Return-1
Problems:
Reading Chinese Character Output Can't Avoid Scrambling
[Example] Read one byte at a time
package com.test.d4_byte_stream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; public class FileInputStreamDemo01 { public static void main(String[] args) throws Exception { // Create a file byte input stream pipeline to connect to the source file. // InputStream is = new FileInputStream(new File("file-io-app\\src\\data.txt")); // Simplified Writing InputStream is = new FileInputStream("file-io-app\\src\\data.txt"); int b; while (( b = is.read() ) != -1){ System.out.print((char) b); } } }
data.txt Content | output |
Hello | Hello |
Hello Hello | ä½ å¥½Hello |
[Example] Read an array of bytes one at a time, with a length of 3
package com.test.d4_byte_stream; import java.io.FileInputStream; import java.io.InputStream; /** Target: Read the data of one byte array at a time using the file byte input stream. */ public class FileInputStreamDemo02 { public static void main(String[] args) throws Exception { // 1. Create a file byte input stream pipeline to connect to the source file InputStream is = new FileInputStream("file-io-app/src/data02.txt"); // 2. Define a byte array for reading byte arrays byte[] buffer = new byte[3]; // 3. Use loops to read one byte array at a time int len; // Record the number of bytes read at a time while ((len = is.read(buffer)) != -1) { // Read how much pour out how much System.out.print(new String(buffer, 0 , len)); } } }
data.txt Content | output |
Hello Hello | Hello Hello |
Hello Hello | Hello������ |
Description: UTF-8 Chinese characters are 3 bytes long. In this case, the byte array length is 3. It is OK to read Chinese characters before them if they are integer multiple of 3 bytes. Otherwise, garbled code will appear because Chinese characters are truncated.
Resolve Scrambling=>Read all bytes at once
You can define an array of bytes as large as a file to read, or you can use the official API
Problems:
Defined byte arrays may cause memory overflow if the file is too large
Method One Defines an array of bytes the same size as a file, which is read at once using the method of reading the array of bytes
Method 2 Public byte[] readAllBytes () throws IOException -> directly loads the byte data of the file object corresponding to the current byte input stream into a byte array and returns it
[Example] Read all bytes at once to avoid scrambling
package com.test.d4_byte_stream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; /** Read all the bytes of the file at once using the file byte input stream. Can solve scrambling problems */ public class FileInputStreamDemo03 { public static void main(String[] args) throws Exception { // 1. Create a file byte input stream pipeline to connect to the source file File f = new File("file-io-app/src/data03.txt"); InputStream is = new FileInputStream(f); // 2. Define a byte array just as large as the file size //byte[] buffer = new byte[(int) f.length()]; //is.read(buffer); // Read all byte arrays byte[] buffer = is.readAllBytes(); System.out.println(new String(buffer)); } }
data03.txt Content
Hello Hello Greeting hello Hi Good morning Morning Have a nice day!Happy everyday
Output:
File byte output stream: FileOutputStream
Write data in memory in bytes to a stream in a disk file based on memory
constructor
public FileOutputStream (File file) ->Create a byte output stream pipeline to connect to the source file object
public FileOutputStream (String filepath) ->Same as above
public FileOutputStream (File file, Boolean append) ->Same as above, data can be appended
public FileOutputStream (String filepath, Boolean append) ->Same as above, appendable data
Write Data Method
Public void write (int a) ->Write a byte out
Public void write (byte[] buffer) ->Write out a byte array
Public void write (byte[] buffer, int pos, int len) ->Write a part of a byte array out
Closing and refreshing of streams
Flush() ->Refresh the stream and continue writing data
Close () -> Close the stream, release resources, and refresh the stream before closing. Once closed, no more data can be written
Byte Output Stream Implements Write Out Data to Wrap Lines
write("\r\n".getBytes())
[Example] Byte Output Stream
package com.test.d4_byte_stream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.OutputStream; /** Use of byte output stream */ public class OutputStreamDemo04 { public static void main(String[] args) throws Exception { // 1. Create a file byte output stream pipeline to connect to the target file OutputStream os = new FileOutputStream("file-io-app/src/out04.txt" , true); // Append Data Pipeline // 2. Write Data Out // a.public void write(int a): write a byte out os.write('a'); os.write(98); os.write("\r\n".getBytes()); // Line Break // b.public void write(byte[] buffer): Write an array of bytes out. byte[] buffer = {'a' , 97, 98, 99}; os.write(buffer); os.write("\r\n".getBytes()); // Line Break byte[] buffer2 = "This is a test".getBytes(); os.write(buffer2); os.write("\r\n".getBytes()); // Line Break // C. public void write (byte[] buffer, int pos, int len): Write a part of a byte array and go out byte[] buffer3 = "This is a test".getBytes(); os.write(buffer3, 3 , 9); os.write("\r\n".getBytes()); // Line Break // os.flush(); // Writing data must refresh data to continue using streams os.close(); // Release resources, including refresh! Closed backflow is not available } }
out04.txt is as follows
ab aabc This is a test Is a
File Copy
Create byte input stream object from data source
Create byte output stream object from destination
Read and write data, copy videos
Release Resources
By traversing folders and copying files
package com.test.d5_resource; import java.io.*; /** Target: Copy Folder */ public class Test4 { public static void main(String[] args) { // D:\resources copy(new File("D:\\resources") , new File("D:\\new")); } public static void copy(File src , File dest){ // 1. Determine whether the source directory exists if(src!= null && src.exists() && src.isDirectory()){ // 2. Destination directory needs to be created D:\new\resources File destOne = new File(dest , src.getName()); destOne.mkdirs(); // 3. Extract all first-level file objects in the original directory File[] files = src.listFiles(); // 4. Determine whether there is a first-level file object if(files != null && files.length > 0) { // 5. Traversing a Level 1 File Object for (File file : files) { // 6. Determine whether it is a file or a folder, or a file that was copied directly to the past if(file.isFile()){ copyFile(file, new File(destOne , file.getName())); }else { // 7. Currently traversing folders, replicating recursively copy(file, destOne); } } } } } public static void copyFile(File srcFile, File destFile){ try ( // 1. Create a byte input stream pipeline to connect to the original video InputStream is = new FileInputStream(srcFile); // 2. Create a byte output stream pipeline to connect to the target file OutputStream os = new FileOutputStream(destFile); ) { // 3. Define a byte array to transfer data byte[] buffer = new byte[1024]; int len; // Record the number of bytes read at a time while ((len = is.read(buffer)) != -1){ os.write(buffer, 0 , len); } } catch (Exception e){ e.printStackTrace(); } } }
After running resources is copied to the new path
try-catch-finally releases resources
Finally: Provide a finally block during exception handling to perform all cleanup operations, such as releasing resources in an IO stream
Feature: finally controlled statements will ultimately execute unless the JVM exits
[Example]
package com.test.d5_resource; import java.io.*; /** Use finally to release resources. */ public class TryCatchFinallyDemo1 { public static void main(String[] args) { InputStream is = null; OutputStream os = null; try { // System.out.println(10/ 0); // 1. Create a byte input stream pipeline to connect to the original video is = new FileInputStream("file-io-app/src/out04.txt"); // 2. Create a byte output stream pipeline to connect to the target file os = new FileOutputStream("file-io-app/src/out05.txt"); // 3. Define a byte array to transfer data byte[] buffer = new byte[1024]; int len; // Records the number of bytes read at a time. while ((len = is.read(buffer)) != -1){ os.write(buffer, 0 , len); } System.out.println("Copy complete!"); // System.out.println( 10 / 0); } catch (Exception e){ e.printStackTrace(); } finally { // Whether the code ends properly or an exception occurs, this is the last place to execute it System.out.println("========finally========="); try { // 4. Close the stream. if(os!=null)os.close(); } catch (IOException e) { e.printStackTrace(); } try { if(is != null) is.close(); } catch (IOException e) { e.printStackTrace(); } } } }
File character input stream: FileReader
Read data from disk files into memory as characters based on memory
constructor
public FileReader - > Create a character input stream pipeline to connect to the source file object
public FileReader (String pathname) ->Same as above
Method
Public int read () ->Returns one character at a time if the character has no readable Return-1
Public int read (char[] buffer) ->Read an array of characters at a time, returning the number of characters read, no readable character returns -1
File character output stream: FileWriter
Write the data in memory as characters to the stream in the disk file based on memory
constructor
Public FileWriter (File file) ->Create a character output stream pipeline to connect to the source file object
public FileWriter (String filepath) ->Same as above
public FileWriter (File file, Boolean append) ->Same as above, data can be appended
public FileWriter (String filepath, Boolean append) ->Same as above
Write Data Method
void write (int c) ->Write a character
void write (char[] cbuf) ->Write an array of characters
void write (char[] cbuf, int off, int len) ->Write part of the character array
void write (String str) ->Write a string
void write (String str, int off, int len) ->Write a part of a string
void write (int c) ->Write a character
Refresh flush() of stream
close() of stream
Scenarios applicable to byte and character streams
Byte streams are good for making copies of all file data (audio, video, text)
Byte stream is not suitable for reading Chinese content output
Character streams are suitable for text file operations (read, write)