18, IO stream
18.1 File class
18.1.1 introduction to file class
- java. io. The file class is an abstract representation of the path names of * * files * * and directories. It is mainly used for the creation, search and deletion of files and directories
- File can be encapsulated into an object file, and the encapsulated object is only a pathname. It may or may not exist.
18.1.2 construction method of file class
Method name | explain |
---|---|
File(String pathname) | Create a new File instance by converting the given pathname string to an abstract pathname |
File(String parent, String child) | Creates a new File instance from the parent pathname string and the child pathname string |
File(File parent, String child) | Create a new File instance from the parent abstract pathname and child pathname strings |
import java.io.File; /** * @author Carl Zhang * @description File Class construction method * @date 2022/1/2 21:36 */ public class FileConstructor { public static void main(String[] args) { //File(String pathname) //Create a new File instance by converting the given pathname string to an abstract pathname File file = new File("D:\\Program Files\\a.txt"); //Saved path D:\Program Files\a.txt System.out.println(file); //File(String parent, String child) //Creates a new File instance from the parent pathname string and the child pathname string File file1 = new File("D:\\Program Files", "a.txt"); //D:\Program Files\a.txt System.out.println(file1); //File(File parent, String child) //Create a new File instance from the parent abstract pathname and child pathname strings File file2 = new File(new File("D:\\Program Files"), "a.txt"); //D:\Program Files\a.txt System.out.println(file2); } }
18.1.3 relative path and absolute path
- Relative path: relative to the path under the current project
- Absolute path: starting from the drive letter
18.2 related methods of file class
18.2.1 creation method
Method name | explain |
---|---|
public boolean createNewFile() | Create a new empty file |
public boolean mkdir() | Failed to create a single level folder if the parent path does not exist |
public boolean mkdirs() ! | Create a multi-level folder. If the parent path does not exist, create the parent path |
import java.io.File; import java.io.IOException; /** * @author Carl Zhang * @description File Class creation function * @date 2022/1/2 21:54 * */ public class FileCreatMethod { public static void main(String[] args) throws IOException { File file1 = new File("D:\\TestFile.txt"); //1 public boolean createNewFile(): creates a new empty file. false is returned if it already exists System.out.println(file1.createNewFile()); //2 public boolean mkdir(): create a single level folder File file2 = new File("D:\\TestFile"); System.out.println(file2.mkdir()); File file3 = new File("D:\\Test\\TestFile"); //False only recognizes the last pathname. The previous D:\Test \ does not exist. Send back false System.out.println(file3.mkdir()); //3 public boolean mkdirs(): create a multi-level folder // If the parent path does not exist, the folder of the parent path will be created together File file4 = new File("D:\\Test\\TestFile"); System.out.println(file4.mkdirs()); //true, create a folder named testfile Txt folder File file5 = new File("D:\\Test\\TestFile.txt"); System.out.println(file5.mkdirs()); } }
18.2.2 deletion method
Method name | explain |
---|---|
public boolean delete() | Delete the file or directory represented by this abstract pathname |
- The delete method deletes directly without going to the recycle bin.
- If you delete a file, delete it directly.
- If you are deleting a folder, you need to delete the contents of the folder before deleting the folder
import java.io.File; import java.io.FileInputStream; import java.io.IOException; /** * @author Carl Zhang * @description File How to delete files and folders * @date 2022/1/2 22:14 */ public class FileDeleteMethod { public static void main(String[] args) throws IOException { File testFile = new File("TestFile"); //System.out.println(testFile.mkdirs()); File file = new File("TestFile\\aaa.txt"); //System.out.println(file.createNewFile()); //Delete file //System.out.println(file.delete()); //Delete empty folder System.out.println(testFile.delete()); //Delete non empty folder File file1 = new File("TestFile\\aaa.txt"); file.mkdirs(); //false System.out.println(testFile.delete()); } }
18.2.2 File class judgment and acquisition
Method name | explain |
---|---|
public boolean isDirectory() | Test whether the File represented by this abstract pathname is a directory |
public boolean isFile() | Test whether the File represented by this abstract pathname is a File |
public boolean exists() | Test whether the File represented by this abstract pathname exists |
public String getAbsolutePath() | Returns the absolute pathname string for this abstract pathname |
public String getPath() | Convert this abstract pathname to a pathname string |
public String getName() | Returns the name of the file or directory represented by this abstract pathname |
package com.heima.file; import java.io.File; import java.io.FileInputStream; import java.io.IOException; /** * @author Carl Zhang * @description File Class judgment and acquisition function * @date 2022/1/2 22:30 */ public class FileGetMethod { public static void main(String[] args) throws IOException { File file1 = new File("TestFile"); File file2 = new File("TestFile\\aaa.txt"); file2.createNewFile(); //public boolean isDirectory() tests whether the File represented by this abstract pathname is a directory System.out.println(file1.isDirectory()); //true System.out.println(file2.isDirectory()); //false //public boolean isFile() tests whether the File represented by this abstract pathname is a File System.out.println(file1.isFile()); //false System.out.println(file2.isFile()); //true //public boolean exists() tests whether the File represented by this abstract pathname exists File testFile123 = new File("TestFile123"); System.out.println(testFile123.exists()); //false System.out.println(file1.exists()); //true System.out.println(file2.exists()); //true //public String getAbsolutePath() returns the absolute pathname string of this abstract pathname System.out.println(file1.getAbsolutePath()); //D:\IDEA_JAVA_Project\chapter18\TestFile System.out.println(file2.getAbsolutePath()); //D:\IDEA_JAVA_Project\chapter18\TestFile\aaa.txt //public String getPath() converts this abstract pathname to a pathname string System.out.println(file1.getPath()); //TestFile System.out.println(file2.getPath()); //TestFile\aaa.txt //public String getName() returns the name of the file or directory represented by this abstract pathname System.out.println(file1.getName()); //TestFile System.out.println(file2.getName()); //aaa.txt } }
18.2.3 File class advanced acquisition method
Method name | explain |
---|---|
public File[] listFiles() | Returns an array of File objects for files and directories in the directory represented by this abstract pathname |
Precautions for listFiles method:
- 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, the paths of all files and folders in it are returned in the File array
- When the caller is a folder with hidden files, the paths of all files and folders in it are returned in the File array, including the hidden contents
import java.io.File; /** * @author Carl Zhang * @description File Class advanced acquisition function * @date 2022/1/2 22:52 */ public class FileGetMethod02 { public static void main(String[] args) { //File chapter18 = new File("..\\"); File chapter18 = new File("..\\"); //File class advanced acquisition function //public File[] listFiles() returns the File object array of files and directories in the directory represented by this abstract pathname File[] files = chapter18.listFiles(); for (File file : files) { System.out.println(file.getName()); } //Precautions for listFiles method: //1. When the caller does not exist, null is returned and an exception is thrown //2 when the caller is a file, null is returned and an exception is thrown //3 when the caller is an empty folder, an array with length 0 is returned //4 when the caller is a folder with content, the paths of all files and folders in it are returned in the File array //5 when the caller is a folder with hidden files, the paths of all files and folders in it are returned in the File array, including the hidden contents } }
18.2.4 exercise 1 - count the number of each file in a folder
package com.heima.file; import java.io.File; import java.util.HashMap; /** * @author Carl Zhang * @description * @date 2022/1/3 13:44 * Exercise 2: count the number of each file in a folder and print it. * <p> * The printing format is as follows: * txt:3 individual * doc:4 individual * jpg:6 individual */ public class Exercise02 { public static void main(String[] args) { //1. Get all File objects under the folder //2. Get the suffix of each file - intercept //3. Save in the map set in the form of key value pairs - {suffix, quantity} //4. Traverse the files array, get a suffix, and save one in the map set. The number is 1 // If the suffix exists, add + 1 to the original number File file = new File("D:\\Yi Jia\\project\\Yijia cloud platform\\test\\test data"); //1. Get all File objects under the folder File[] files = file.listFiles(); //Suffix and quantity used to store statistics HashMap<String, Integer> hashMap = new HashMap<>(); for (File file1 : files) { //Get the suffix of each file - intercept - because Is regular, so add escape characters String[] split = file1.getName().split("\\."); //If it is a.b.c.txt, it is {a, b, c, txt}, and the suffix is the last element String type = split[split.length - 1]; //If the suffix exists, add + 1 to the original number if (hashMap.containsKey(type)) { hashMap.put(type, hashMap.get(type) + 1); continue; } //If the suffix does not exist, it is added to the collection hashMap.put(type, 1); } //Print System.out.println(hashMap); } }
18.2.5 exercise 2 - delete folders recursively
import java.io.File; /** * @author Carl Zhang * @description Use recursion to delete the specified folder on the computer * @date 2022/1/3 14:21 */ public class DeleteFiles { public static void main(String[] args) { //Analysis: if the folder is not empty, delete the files under the folder first and then delete the folder //1. Exit condition: empty folder or file, delete directly - call file delete(),return //2. Non empty folder: delete all files under the folder first, and then delete the folder -- get Directory - call the method circularly File file = new File("D:\\Test folder\\TestFile02"); deleteFiles(file); } /** * Pass in file and delete all files under the path * @param file Files / folders to delete * @return Delete result */ public static void deleteFiles(File file) { //If it is a file or an empty folder, it will be deleted directly and returned if (file.delete()) { return; } //Otherwise, it is a non empty folder. Delete the files in it first File[] files = file.listFiles(); for (File file1 : files) { deleteFiles(file1); } //Then delete the current folder file.delete(); } }
18.3 introduction to IO flow
18.3.1 reasons for learning IO flow
Previously, data was stored through variables, arrays, or collections
Problem:
- Can not be stored permanently, because the data is stored in memory
- As long as the code runs, all data will be lost
Outgoing use IO stream
characteristic:
-
Write the data to the file to realize the permanent storage of data
-
Read the data in the file into memory (Java program)
18.3.2 introduction to IO flow
- I ^ stands for input. It is the process of data from hard disk into memory, which is called reading.
- O stands for output, which is the process of data from memory to hard disk. Call it writing
- IO data transmission can be regarded as a kind of data flow. According to the flow direction, read and write operations are carried out with memory as the reference
- Simply put: memory is reading and memory is writing
18.3.3 IO stream classification
Classification:
- Distinguish according to flow direction
- Input stream: used to read data
- Output stream: used to write data
- By type
- Byte stream
- Character stream
be careful:
- Byte stream can operate on any file
- Character streams can only manipulate plain text files
- If you can read it with windows Notepad, such a file is a plain text file.
18.4 byte output stream
18.4.1 byte output stream introduction
Introduction to FileOutputStream class
- OutputStream output stream has many subclasses. Let's start with the simplest subclass.
- java. io. The fileoutputstream class is a file output stream used to write data out to a file
Construction method:
- public FileOutputStream(File file): creates a File output stream to write to the File represented by the specified File object.
- public FileOutputStream(String name): creates a file output stream and writes it to the file with the specified name.
be careful:
- If the specified file does not exist, it will be automatically created
- If the specified file exists, the contents of the file will be emptied first
package com.heima.outputstream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; /** * @author Carl Zhang * @description FileOutPutStream Construction method demonstration * @date 2022/1/3 17:34 */ public class OutputStream01 { public static void main(String[] args) throws IOException { //-public FileOutputStream(File file): creates a File output stream to write to the File represented by the specified File object. //1. If the specified file does not exist, it will be automatically created //2. If the specified file exists, the contents of the file will be emptied first File file = new File("aaa.txt"); FileOutputStream fileOutputStream1 = new FileOutputStream(file); //-public FileOutputStream(String name): creates a file output stream and writes it to the file with the specified name. // At the bottom layer, this (name! = null? New file (name): null, false) creates a file object FileOutputStream fileOutputStream2 = new FileOutputStream("aaa.txt"); } }
18.4.2 byte output stream write data steps
- Creates a byte output stream object.
- Write data
- The integer written out is actually the letter corresponding to the integer on the code table.
- Release resources
- Resources must be released each time the stream is used.
import java.io.FileOutputStream; import java.io.IOException; /** * @author Carl Zhang * @description Byte output stream write data quick start * @date 2022/1/3 17:46 */ public class OutputStream02 { public static void main(String[] args) throws IOException { //-Creates a byte output stream object. FileOutputStream fileOutputStream = new FileOutputStream("aaa.txt"); //-Write data // What is written is a byte 99. It shows the c translated according to the ASCII table. What is actually stored is still 99 fileOutputStream.write(99); //-Release resources to avoid occupying the corresponding file // close() closes the file output stream and frees all system resources associated with the stream. This file output stream can no longer be used to write bytes fileOutputStream.close(); } }
18.4.3 byte output stream writing method
Method name | explain |
---|---|
void write(int b) | Write one byte of data at a time |
void write(byte[] b) | Write one byte array data at a time |
void write(byte[] b, int off, int len) | Write some data of a byte array at a time |
import java.io.FileOutputStream; import java.io.IOException; /** * @author Carl Zhang * @description Method for writing data in byte output stream * @date 2022/1/3 17:59 */ public class OutputStream03 { public static void main(String[] args) throws IOException { //Get byte stream object FileOutputStream fileOutputStream = new FileOutputStream("aaa.txt"); //-1 void write(int b) write one byte of data at a time fileOutputStream.write(99); fileOutputStream.write('a'); // 'a' -> 98 -> a //-2 void write(byte[] b) write byte array data one at a time byte[] b = {98, 99, 100}; fileOutputStream.write(b); //bcd //-3 void write(byte[] b, int off, int len) writes part of the data of a byte array at a time // off - start subscript. Head without tail fileOutputStream.write(b, 0, 2); //bc //Question: how to write a string one at a time //Get the indirect output of byte array through getBytes() method fileOutputStream.write("hello,world".getBytes()); //Close flow fileOutputStream.close(); } }
18.4.4 byte output stream additional write and line feed
- How to wrap byte stream write data? Add a line break after writing the data
- windows : \r\n
- linux : \n
- mac : \r
- How to realize additional writing of byte stream write data?
- Construction method: public FileOutputStream(String name, boolean append)
- Creates a file output stream and writes to the file with the specified name. If the second parameter is true, the contents of the file will not be cleared
package com.heima.outputstream; import java.io.FileOutputStream; import java.io.IOException; /** * @author Carl Zhang * @description Line feed and append write of byte stream write data * @date 2022/1/3 18:15 */ public class OutputStream04 { public static void main(String[] args) throws IOException { FileOutputStream fileOutputStream = new FileOutputStream("aaa.txt"); //How to wrap 1-byte stream write data? // Add a line break after writing the data // windows : \r\n // linux : \n // mac : \r fileOutputStream.write(98); //You cannot write a string directly. You need to use the getBytes() method fileOutputStream.write("\r\n".getBytes()); fileOutputStream.write(99); fileOutputStream.write("\r\n".getBytes()); fileOutputStream.write(100); //How to realize additional writing of 2-byte stream write data? // Construction method: public FileOutputStream(String name, boolean append) // Creates a file output stream and writes to the file with the specified name. If the second parameter is true, the contents of the file will not be cleared FileOutputStream fileOutputStream2 = new FileOutputStream( "bbb.txt", true); //fileOutputStream2.write("hello,".getBytes()); fileOutputStream2.write("world!".getBytes()); //hello,world! } }
18.5 byte input stream
18.5.1 byte input stream introduction
Byte input stream class
- InputStream class: the topmost class and abstract class of byte input stream
- FileInputStream class: FileInputStream extensions InputStream
Construction method
- Public FileInputStream (file): read data from the path of file type
- public FileInputStream(String name): reads data from the string path
step
- Create an input stream object
- If the file does not exist, an error will be reported directly.
- Read data
- What is read out is the code table value of the data in the file. a 97
- Release resources
- Resources must be released each time the stream is used.
18.5.2 case of reading one byte at a time
package com.heima.inputstream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; /** * @author Carl Zhang * @description Read one byte at a time * @date 2022/1/3 20:36 */ public class InputStream01 { public static void main(String[] args) throws IOException { //1 create input stream object FileInputStream fileInputStream = new FileInputStream("bbb.txt"); //2 read data // Returned is a byte of type int // If you want to see characters, you need to turn strongly int read = fileInputStream.read(); System.out.println((char) read); //3 release resources fileInputStream.close(); } }
18.5.3 case of reading multiple bytes at a time
import java.io.FileInputStream; import java.io.IOException; /** * @author Carl Zhang * @description Read multiple bytes at a time * @date 2022/1/3 20:36 */ public class InputStream01 { public static void main(String[] args) throws IOException { //Part III: byte input stream steps //1 create input stream object //java.io.FileNotFoundException: bbb.txt (the system cannot find the specified file.) //The file pointed to by the path does not exist, and an exception will be thrown FileInputStream fileInputStream = new FileInputStream("bbb.txt"); //2 read data // Receive read data int read; // Each time the read() method executes, it points to the last byte - analog iterator Next() method // If you finish reading, it will return - 1 while ((read = fileInputStream.read()) != -1) { System.out.print((char) read); } //3 release resources fileInputStream.close(); } }
18.5.4 copy case of documents - copy pictures
import java.io.*; /** * @author Carl Zhang * @description copy picture * @date 2022/1/3 21:05 */ public class CopyPicture { public static void main(String[] args) throws IOException { //Idea: read a byte of a file and write a byte //1. Create a character input stream according to the image path to be copied FileInputStream fileInputStream = new FileInputStream("" + "D:\\Yi Jia\\project\\Yijia cloud platform\\test\\test data\\Announcement test picture 1.jpg"); //2. Create a character output stream according to the path of the picture to be stored FileOutputStream fileOutputStream = new FileOutputStream("Announcement test picture.jpg"); //3. Read the bytes of the picture circularly, and write one for each read //Save read bytes int read; while ((read = fileInputStream.read()) != -1) { fileOutputStream.write(read); } //4. Release resources in order fileInputStream.close(); fileOutputStream.close(); } }
18.5.5 resource release optimization of JDK7
JDK7 used to release resources manually. The code is too complex
package com.itheima.inputstream_demo; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; /* Requirement: capture the code of the last assigned image */ public class FileInputStreamDemo4 { public static void main(String[] args) { FileInputStream fis = null ; FileOutputStream fos = null; try { // Create byte input stream object fis = new FileInputStream("D:\\Intelligence Podcast\\Installation package\\Nice picture\\liqin.jpg"); // Create byte output stream fos = new FileOutputStream("day11_demo\\copy.jpg"); // Read and write one byte at a time int by; while ((by = fis.read()) != -1) { fos.write(by); } } catch (IOException e) { e.printStackTrace(); } finally { // Release resources if(fis != null){ try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } // Release resources if(fos != null){ try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
JDK7 version optimization processing method: automatically release resources
- After JDK7 optimization, you can use the try with resource statement, which ensures that each resource is automatically closed at the end of the statement.
Simple understanding: using this statement will automatically release resources. You don't need to write finally code blocks - Format:
try (Create stream object statement 1 ; Create stream object statement 2 ...) { // Read and write data } catch (IOException e) { Code to handle exceptions... }
- Case: capture the code of the last assigned image
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; /** * @author Carl Zhang * @description Capture the code of the last assigned picture * @date 2022/1/3 21:26 */ public class CloseResource { public static void main(String[] args) throws IOException { try ( //Write the statement to create the stream object from try() FileInputStream fileInputStream = new FileInputStream("" + "D:\\Yi Jia\\project\\Yijia cloud platform\\test\\test data\\Announcement test picture 1.jpg"); FileOutputStream fileOutputStream = new FileOutputStream("Announcement test picture.jpg") ) { //Cycle to read the bytes of the picture. Each time you read one, write one //Save read bytes int read; while ((read = fileInputStream.read()) != -1) { fileOutputStream.write(read); } //When the resource is released, it is found that it is gray, prompting redundant code. Therefore, using the try with resource method will automatically close the flow //fileInputStream.close(); //fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
18.5.6 case of reading one byte array at a time
Problem: if the file is too large, the original way of reading one byte at a time will be very slow
Solution: in order to solve the speed problem, read the data of byte stream into byte array to improve the reading efficiency.
method:
- Method to read one byte array at a time:
- public int read(byte[] b): reads data of up to b.length bytes from the input stream, and returns the number of data actually read
- Returns the number of data actually read
- String construction method:
- public String(byte bytes[], int startIndex, int length) returns a string object of bytes of the specified length in the byte array
Case 1:
package com.heima.inputstream; import java.io.FileInputStream; import java.io.IOException; /** * @author Carl Zhang * @description Byte input stream reads one byte array at a time * @date 2022/1/3 22:01 */ public class ReadByteArray { public static void main(String[] args) { //Create a byte input stream object //Use the try with resource method to automatically close the flow try (FileInputStream fileInputStream = new FileInputStream("bbb.txt")) { //Create an array to hold the read data byte[] read = new byte[3]; //From BBB Txt reads bytes from the read array //len is the number of bytes actually read each time int len = fileInputStream.read(read); //Print the number of bytes read System.out.println(len); //3 //Pass in the byte array through the construction method to obtain the corresponding string System.out.println(new String(read)); //abc //Second read //int len2 = fileInputStream.read(read); //System.out.println(len2); //2 //System.out.println(new String(read)); //dec, because only two bytes are read, only the first two bytes in the array are replaced //improvement //int len2 = fileInputStream.read(read); //System.out.println(len2); //2 //public String(byte bytes[], int startIndex, int length), which only converts the two numbers read into strings //System.out.println(new String(read, 0, len2)); //Get multiple bytes by loop //Usually a multiple of 1024 byte[] bytes = new byte[1024]; //Save the number of bytes read each time int leng; //When the number of bytes read is - 1, there is no content while ((leng = fileInputStream.read(bytes)) != -1) { //Convert the read bytes into a string for printing System.out.println(new String(bytes, 0, leng)); } } catch (IOException e) { e.printStackTrace(); } } }
Case 2: improve the way of reading and writing one byte array at a time by using the code for copying pictures
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; /** * @author Carl Zhang * @description The code for copying pictures is used to improve the way of reading and writing a byte array at a time * @date 2022/1/3 22:37 */ public class CopyPicture02 { public static void main(String[] args) { try ( //Create a byte input stream object for the picture to be copied FileInputStream fileInputStream = new FileInputStream("" + "D:\\Yi Jia\\project\\Yijia cloud platform\\test\\test data\\Announcement test picture 1.jpg"); //Create a byte input stream object of the path where the picture is to be stored FileOutputStream fileOutputStream = new FileOutputStream( "Announcement test picture.jpg") ) { //Read byte array and output byte[] bytes = new byte[1024]; int len; while ((len = fileInputStream.read(bytes)) != -1) { //Output the real number of bytes read each time fileOutputStream.write(bytes, 0, len); } } catch (IOException e) { e.printStackTrace(); } } }