Learning objectives
- Can say File How objects are created(Must be) Using construction methods public File(String pathname) : Creates a new path name by converting the given path name string to an abstract path name File example. public File(String parent, String child) : Creates a new path from the parent pathname string and the child pathname string File example. public File(File parent, String child) : Creates a new path from the parent abstract pathname and child pathname strings File example. - Can use File Class common methods(Must be) public String getName() : Gets the name of the path in the constructor(tail) public String getAbsolutePath() : Gets the absolute path of the path in the constructor public long length() : Gets the size of the file,The unit is byte public boolean isDirectory() : Is it a directory(folder). public boolean exists() : Judge whether the path passed in the construction method exists public boolean createNewFile() : Create a new empty file if and only if the file with that name does not already exist. public boolean mkdir() : Create a single level folder public boolean mkdirs() : You can create a single level folder,You can also create multi-level folders public boolean delete() : Delete files and folders,No recycle bin - Be able to distinguish between relative path and absolute path(Must be) absolutely:Start with drive letter relative:Relative to the root directory of the current project;Use the following table of contents of the project to omit writing(Not a drive letter) absolutely:D:\\Work_idea\\EE132\\day15\\a.txt relative:day15\\a.txt The root directory of the project D:\\Work_idea\\EE132 - Ability to traverse folders(Must be) public String[] list() : Traverses the folder passed by the constructor,Get every file in the folder|The name of the subfolder,Store multiple names in one String Type public File[] listFiles() : Return a File Array representing the File All sub files or directories in the directory. Traverses the folder passed by the constructor,Get every file in the folder|Subfolder,File|Subfolders are encapsulated as File object,Multiple File Object stored in a File Type - Can explain the meaning of recursion Method calls itself - The factorial of 5 can be calculated recursively(Must be) public static int jc(int n) {//The main body of the method remains unchanged, and its parameters change 5,4,3,2,1 every time it is called //Condition for the end of recursion: it ends when 1 is obtained if(n==1){ return 1; } //The purpose of recursion: get the next multiplied number n-1 return n * jc(n-1); } - Be able to tell the reason why using recursion will cause memory overflow Method calls itself,No end condition,There are countless methods in stack memory,If there are too many methods out of the stack memory range, a memory overflow will occur - Can say IO Classification and function of flow Input stream:Put the hard disk(U disc,mobile hard disk drive,disk,CD...)The data on is read into memory Character input stream:Read character Byte input stream:Read byte Output stream:Write the data in memory to the hard disk(U disc,mobile hard disk drive,disk,CD...) Character output stream:Write character Byte output stream:Write byte - Ability to write data to a file using a byte output stream(Must be) 1.establish FileOutputStream object,The destination where the write data is passed in the constructor 2.call FileOutputStream Methods in objects write,Write data to a file 3.Release resources FileOutputStream fos = new FileOutputStream("day10\\1.txt"); fos.write(97); fos.close(); - The ability to read data to a program using a byte input stream 1.establish FileInputStream object,Bind the data source to be read in the constructor FileInputStream fis = new FileInputStream("day15\\a.txt"); 2.FileInputStream Methods in objects read,Read files in bytes int len = 0; while ((len = fis.read())!=-1){ System.out.print((char)len); } 3.Release resources fis.close(); - Be able to understand and read data read(byte[])Principle of method 1.read Method parameters byte[]Function of byte array? Play a buffer role,Store the read bytes in the array in turn The array is returned to by the operating system at one time JVM,from JVM Return to java program,efficient The length of the array is generally used:1024 Or an integer multiple of 1024 2.read Method int What is it?? Number of valid bytes read each time FileInputStream fis = new FileInputStream("day15\\a.txt"); byte[] bytes = new byte[1024]; int len = 0; while ((len = fis.read(bytes))!=-1){ System.out.print(new String(bytes,0,len)); } fis.close(); - Can use byte stream to copy files(Read and write) 1.establish FileInputStream object,Bind the data source to be read in the constructor 2.establish FileOutputStream object,Bind the destination to be written in the constructor 3.use FileInputStream Methods in objects read,Read files in bytes 4.use FileOutputStream Methods in objects write,Write the read bytes to the file 5.Release resources
Chapter 1 File class
1. Introduction to file class
java.io.File class Abstract representation of file and directory pathnames. Put the files and folders in the computer(catalogue)Package for File object,You can use File Object to manipulate these files and folders We can use File Object to create files and folders We can use File Object to delete files and folders We can use File Object to get the path of files and folders We can use File Object to get the size of the file(The unit is byte) We can use File Object traverses the folder Remember three related words: 1.file:file 2.directory:folder(catalogue) 3.path:route
2. Path
route:Represents the path where files and folders are stored(position) classification: 1.Absolute path:Path starting with drive letter(c:,d:,e:) c:\\1.jpg d:\\aaa\\a.txt D:\\Work_idea\\EE141\\day10 2.Relative path:Relative to the root directory of the current project,We use paths,You can omit the root directory of the project The root directory of the project:D:\\Work_idea\\EE119 EE119:Create a project be careful:Everyone's project root directory is different a.Absolute path[Must contain the root directory of the project]Can be omitted D:\\Work_idea\\EE119\\day10 Can be omitted as day10 D:\\Work_idea\\EE119\\day10\\a.txt Can be omitted as day10\\a.txt c:\\1.jpg Cannot be omitted 1.jpg==> D:\Work_idea\EE119\\1.jpg abc\\bbc\\ccc\\abc.java==>D:\\Work_idea\\EE119\\abc\\bbc\\ccc\\abc.java b.When we omit the root directory of the writing item,java The default path is added to the before the relative path be careful: 1.Paths are case insensitive c:\\1.jpg equivalence C:\\1.jpg 2.Split symbol for directory in path\You must write two\\,\Itself is an escape character,You must write two for one\ 3.A forward slash can also be used for the split symbol of the directory in the path/ c:\\a.txt equivalence c:/a.txt
3. Construction method of file (key points)
package com.itheima.demo01File; import java.io.File; /* File Construction method of (key) */ public class Demo01FileConstructor { public static void main(String[] args) { show02("d:\\aaa","a.txt");//d:\aaa\a.txt show02("c:\\","a.txt");//c:\a.txt show02("c:\\","aaa\\bbb\\ccc");//c:\aaa\bbb\ccc show03(); } /* File(File parent, String child) Create a new File instance based on the parent abstract pathname and the child pathname string. Parameter: divides the path into two parts File parent:Parent path String child:Sub path Benefits: When creating a File object, the parent path and child path are specified respectively, which can form different paths */ private static void show03() { File parent = new File("d:\\aaa"); File file = new File(parent,"a.txt"); System.out.println(file);//d:\aaa\a.txt } /* File(String parent, String child) Create a new File instance based on the parent pathname string and the child pathname string. Parameter: divides the path into two parts String parent:Parent path String child:Sub path Benefits: When creating a File object, the parent path and child path are specified respectively, which can form different paths */ private static void show02(String parent, String child) { File file = new File(parent,child); System.out.println(file); } /* File(String pathname) Create a new File instance by converting the given pathname string to an abstract pathname. Parameters: String pathname:Pass a path name be careful: 1.The path name passed can be absolute or relative 2.The path name passed can end in a file or in a folder 3.The path name passed can be real or fabricated in the computer The construction method only encapsulates the path of the string as a File object, regardless of the real situation of the path */ private static void show01() { File f1 = new File("c:\\1.jpg"); System.out.println(f1);//c:.jpg is not the address value of the Object. The File class overrides the toString method of the Object class File f2 = new File("D:\\Work_idea\\EE169\\day10"); System.out.println(f2);//D:\Work_idea\EE169\day10 File f3 = new File("day10"); System.out.println(f3);//day10 File f4 = new File("day10/aaa/bbb/cc/ddd"); System.out.println(f4);//day10\aaa\bbb\cc\ddd } }
4. Member method of file class_ Methods of obtaining functions (key points)
public String getAbsolutePath() : Return to this File Absolute pathname string for. public String getPath() : Will this File Convert to pathname string. public String getName() : Return from File Represents the name of the file or directory. public long length() : Return from File Represents the length of the file. Cannot get the length of the directory
package com.itheima.demo01File; import java.io.File; /* File Class to get related methods */ public class Demo02FileMethod { public static void main(String[] args) { show04(); } /* public long length() : Returns the size of the File represented by this File. Cannot get the size of the directory. be careful: 1.The unit of file size is bytes 2.This method can only get the file size, not the folder size (the folder has no size concept) If this pathname represents a directory (folder), the return value is uncertain. 3.If the file does not exist, 0L is returned */ private static void show04() { File f1 = new File("D:\\base\\20210908EE169\\day10-File Class, recursion, byte stream\\day10 Courseware\\day10-File Class, recursion, byte stream.pptx"); System.out.println(f1.length());//3092266 bytes File f2 = new File("day10\\1.jpg"); System.out.println(f2.length());//161548 bytes File f3 = new File("day10\\2.jpg"); System.out.println(f3.length());//0L file does not exist File f4 = new File("D:\\Work_idea\\EE169\\day10"); System.out.println(f4.length());//0 4096 folder has no concept of size } /* public String getName(): Gets the name of the end of the path in the construction method */ private static void show03() { File f1= new File("D:\\Work_idea\\EE169\\day10"); System.out.println(f1.getName());//day10 File f2 = new File("c:\\aaa\\1.jpg"); System.out.println(f2.getName());//1.jpg } /* public String getPath() : Returns the path passed in the constructor If the path passed in the constructor is absolute, the absolute path is returned If the path passed in the constructor is relative, the relative path is returned File Class overrides the toString method of the Object class public String toString() { return getPath(); } */ private static void show02() { File f1= new File("D:\\Work_idea\\EE169\\day10"); System.out.println(f1.getPath());//D:\Work_idea\EE169\day10 File f2 = new File("day10"); System.out.println(f2.getPath());//day10 System.out.println(f2);//day10 System.out.println(f2.toString());//day10 } /* Absolute:absolute public String getAbsolutePath() : Gets the absolute path of the pass path in the constructor. The path passed in the constructor is absolute, and the absolute path is returned directly The path passed in the construction method is relative. The project root directory will be added before the relative path to form an absolute path return */ private static void show01() { File f1 = new File("c:\\1.jpg"); System.out.println(f1.getAbsolutePath());//c:\1.jpg File f2 = new File("D:\\Work_idea\\EE169\\day10"); System.out.println(f2.getAbsolutePath());//D:\Work_idea\EE169\day10 File f3 = new File("day10"); System.out.println(f3.getAbsolutePath());//D:\Work_idea\EE169\day10 } }
5. Member method of file class_ Methods for judging functions (key points)
public boolean exists() : this File Indicates whether the file or directory actually exists. public boolean isDirectory() : this File Indicates whether the is a directory. public boolean isFile() : this File Indicates whether the is a file.
package com.itheima.demo01File; import java.io.File; /* File Member method of class_ Methods for judging functions (key points) public boolean exists() : Whether the File or directory represented by this File actually exists. public boolean isDirectory() : This File indicates whether it is a directory. public boolean isFile() : This File indicates whether it is a File. */ public class Demo03FileMethod { public static void main(String[] args) { show02(); } /* public boolean isDirectory() : Determine whether the path passed in the construction method ends in a folder Return value: boolean End with folder: return true Not ending in folder: false returned public boolean isFile() : Judge whether the path passed in the construction method ends in a file Return value: boolean End with file: returns true Not ending in file: returns false be careful: 1.The premise of the above two methods is that the path must be real, otherwise both return false 2.In the computer, all two methods are mutually exclusive except that files are folders */ private static void show02() { File f1 = new File("c:\\adsfdsafdsa"); System.out.println(f1.isDirectory());//false System.out.println(f1.isFile());//false System.out.println("--------------------------------"); File f2 = new File("c:\\1.jpg"); if(f2.exists()){ System.out.println(f2.isDirectory());//false System.out.println(f2.isFile());//true } System.out.println("--------------------------------"); File f3 = new File("day10"); if(f3.exists()){ System.out.println(f3.isDirectory());//true System.out.println(f3.isFile());//false } } /* public boolean exists() : Whether the File or directory represented by this File actually exists. Return value: boolean If the file folder in the constructor exists, return true The file folder in the constructor does not exist, and false is returned */ private static void show01() { File f1 = new File("c:\\1.jpg"); System.out.println(f1.exists());//true File f2 = new File("day10"); System.out.println(f2.exists());//true File f3 = new File("day10\\aaa"); System.out.println(f3.exists());//false } }
6. Member method of file class_ Methods of creating and deleting functions (key points)
public boolean createNewFile() : Create a new empty file if and only if the file with that name does not already exist. public boolean mkdir() : Create this File Represents the directory of the. public boolean mkdirs() : Create this File Represents the directory, including any parent directory that is required but does not exist. public boolean delete() : Delete this File Represents a file or directory.
package com.itheima.demo01File; import java.io.File; import java.io.IOException; /* File Member method of class_ Methods of creating and deleting functions (key points) public boolean createNewFile() : Create a new empty file if and only if the file with that name does not already exist. public boolean mkdir() : Create the directory represented by this File. public boolean mkdirs() : Create the directory represented by this File, including any required but nonexistent parent directory. public boolean delete() : Delete the File or directory represented by this File. */ public class Demo04FileMethod { public static void main(String[] args) throws IOException { show03(); } /* delete:delete public boolean delete() : Delete the file and folder pointed to by the path in the construction method Return value: boolean The file | folder exists. The deletion is successful. Return true File | folder does not exist, deletion failed, return false There is data in the folder. Deletion failed and false is returned be careful: This deletion method does not go through the recycle bin, but is directly deleted on the hard disk. You need to be careful */ private static void show03() { File f1 = new File("day10\\1.txt"); boolean b1 = f1.delete(); System.out.println("b1:"+b1); File f2 = new File("day10\\aaa"); boolean b2 = f2.delete(); System.out.println("b2:"+b2); File f3 = new File("day10\\111"); boolean b3 = f3.delete(); System.out.println("b3:"+b3); } /* mk:make Manufacturing, create dir:directory folder public boolean mkdir() : Only single level folders can be created public boolean mkdirs() : You can create both single level folders and multi-level folders Return value: boolean Folder does not exist, created successfully, return true The folder already exists and will not be created (overwritten). If the creation fails, false is returned; Path does not exist, return false be careful: 1.The path and name of the created folder are given in the construction method 2.The above two methods can only create folders, not files */ private static void show02() { File f1 = new File("day10\\aaa"); boolean b1 = f1.mkdir(); System.out.println("b1:"+b1); File f2 = new File("day10\\111\\222\\333\\444\\555"); boolean b2 = f2.mkdirs(); System.out.println("b2:"+b2); File f3 = new File("e:\\name"); boolean b3 = f3.mkdir(); System.out.println("b3:"+b3);//b3:false path does not exist } /* create:Create, new: new File: public boolean createNewFile() : Create a new empty file if and only if the file with that name does not already exist. Return value: boolean The file does not exist. It is created successfully and returns true The file already exists and will not be created (overwritten). If the creation fails, false will be returned be careful: 1.The path and name of the created file are given in the construction method 2.This method can only create files, not folders 3.If the path to create the file does not exist, an exception will be thrown 4.Some operating system c disks do not have permission to create files, and exceptions will be thrown */ private static void show01() throws IOException { File f1 = new File("d:\\a.txt"); boolean b1 = f1.createNewFile(); System.out.println("b1:"+b1); File f2 = new File("day10\\1.txt"); boolean b2 = f2.createNewFile(); System.out.println("b2:"+ b2); File f3 = new File("e:\\2.txt"); //boolean b3 = f3.createNewFile();//IOException: the system cannot find the specified path. File f4 = new File("d:\\abcsafa\\3.txt"); //boolean b4 = f4.createNewFile();//IOException: the system cannot find the specified path. abcsafa folder does not exist } }
7. Member method of file class_ Directory traversal method (emphasis)
package com.itheima.demo01File; import java.io.File; /* File Member method of class_ Directory traversal method (emphasis) A directory is also called a folder String[] list() It is used to traverse the directory, obtain the name of each file and folder in the directory, store multiple names in a String type array and return File[] listFiles() It is used to traverse the directory and obtain each File folder in the directory. The File folder will be encapsulated as a File object, and multiple File objects will be stored in an array of File type and returned matters needing attention: 1.The path of the directory to be traversed is given in the construction method 2.The above two methods can only traverse directories, not files, and will throw a null pointer exception 3.If the path traversing the directory does not exist, a null pointer exception will be thrown */ public class Demo05FileMethod { public static void main(String[] args) { //File file = new File("e:\\aaa");//NullPointerException //File file = new File("d:\\aaa\\1.jpg");//NullPointerException File file = new File("D:\\aaa"); String[] arr = file.list(); System.out.println(arr); //In work, before traversing arrays and collections, non null judgment should be added to prevent null pointer exceptions if(arr!=null && arr.length>0){ for (String fileName : arr) { System.out.println(fileName); } } System.out.println("-------------------"); File[] files = file.listFiles(); System.out.println(files); if(files!=null && files.length>0) { for (File f : files) { System.out.println(f); } } }
8. Comprehensive exercise of file directory traversal
package com.itheima.demo01File; import java.io.File; import java.util.Scanner; /* File Class directory traversal comprehensive exercise Requirements: Enter a File path with the keyboard, create a File object according to the File path, and judge whether it is a File or a folder If it is a file, the size of the output file If it is a folder, calculate the sum of all file sizes under the folder and output it (excluding subfolders). analysis: 1.Create a keyboard entry Scanner object 2.Receive the string path entered by the keyboard 3.Creates a file object based on a string path 4.Judge whether the file object is a file or a folder. If it is a file, directly output the file size 5.If it is a folder 5.1 Define a summation variable to record the cumulative summation 5.2 Traverse the folder to get all the files under the folder 5.3 Get the file size and add it to the summation variable 5.4 Finally, the value of the summation variable is output. */ public class Demo06FileTest { public static void main(String[] args) { //1. Create a keyboard entry Scanner object Scanner sc = new Scanner(System.in); //2. Receive the string path entered by the keyboard System.out.println("Please enter a file|Path to folder:"); String path = sc.nextLine(); //3. Create a file object according to the string path File file = new File(path); //Determine whether the file exists if(file.exists()){ //4. Judge whether the file object is a file or a folder, if(file.isFile()){ //If it is a file, the file size is output directly System.out.println("The path you entered is a file,The file size is:"+file.length()+"byte"); }else{ //5. If it is a folder //5.1 define a summation variable and record the cumulative summation long sum = 0; //5.2 traverse the folder to obtain all the files under the folder File[] files = file.listFiles(); //Prevent null pointer exceptions, traverse the array and increase non null judgment if(files!=null && files.length>0){ for (File f : files) { //5.3 get the file size and add it to the summation variable sum+=f.length(); } } //5.4 finally output the value of summation variable. System.out.println("The path you entered is a folder,The size of all files in the folder is:"+sum+"byte"); } }else{ System.out.println("The path you entered does not exist!"); } } }
Chapter 2 recursion
1. Overview of recursion
recursion:Method calls itself classification: 1.Direct Recursion public void a(){ a(); } 2.Indirect recursion public void a(){ b(); } public void b(){ a(); } matters needing attention: 1.Recursion must have an end condition,Ensure that the method itself calls and stops,Otherwise, a stack memory overflow error will be thrown 2.Recursion has an end condition,But the number of recursions can't be too many,Otherwise, a stack memory overflow error will be thrown 3.Constructors prohibit recursion When to use recursion: When we call a method frequently,The body of the method remains unchanged,The parameters of the method change each time,You can use recursion
package com.itheima.demo02Recursion; /* Precautions for recursion: 1.Recursion must have an end condition to ensure that the method can stop calling itself, otherwise it will throw an error of stack memory overflow 2.Recursion has an end condition, but the number of recursions should not be too many, otherwise an error of stack memory overflow will be thrown 3.Constructors prohibit recursion */ public class Demo01DiGui { public static void main(String[] args) { //a(); b(1); } /* 3.Constructors prohibit recursion */ public Demo01DiGui() { //Demo01DiGui(); } /* 2.Recursion has an end condition, but the number of recursions should not be too many, otherwise an error of stack memory overflow will be thrown 11413 11410 The number of methods is not absolute, and the memory utilization is changing at any time Exception in thread "main" java.lang.StackOverflowError */ private static void b(int i) { System.out.println(i); if(i==20000){ return;//End method } b(++i); } /* 1.Recursion must have an end condition to ensure that the method can stop calling itself, otherwise it will throw an error of stack memory overflow Exception in thread "main" java.lang.StackOverflowError */ private static void a() { System.out.println("a method"); a(); } }
2. Exercise: use recursion to calculate the sum of 1-n
package com.itheima.demo02Recursion; /* Exercise: use recursion to calculate the sum of 1 ~ n analysis: Recursion means that the method calls itself. You must define a summation method and call your own summation Formula: the sum of 1-n is equivalent to the sum of n-1 n+(n-1)+(n-2)+(n-3)+...+1 5+(5-1)+(4-1)+...+1 Known: n:Transfer 101001000 1:Add to 1 end unknown: n-1 The purpose of recursion: get the next added number n-1 Condition for the end of recursion: it ends when 1 is obtained */ public class Demo02DiGui { public static void main(String[] args) { int sum = getSum(100); System.out.println(sum); } /* Define a summation method and call it yourself */ public static int getSum(int n){//5,4,3,2,1 //Condition for the end of recursion: it ends when 1 is obtained if(n==1){ return 1; } //The purpose of recursion: get the next added number n-1 return n + getSum(n-1); } }
3. Exercise: recursive factorization (key)
package com.itheima.demo02Recursion; /* Exercise: recursive factorization (key) The difference between demonstration and summation is enough analysis: Recursion means that the method calls itself. You must define a factorial method and call yourself to find the factorial Formula: the sum of 1-n is equivalent to the sum of n-1 5 Factorial 5= 5*4*3*2*1; n Factorial n= n*(n-1)*(n-2)*(n-3)*...1; Known: n:Pass it on 5,10 1:Multiply to 1 unknown: n-1 The purpose of recursion: get the next multiplied number n-1 Condition for the end of recursion: it ends when 1 is obtained */ public class Demo03DiGUi { public static void main(String[] args) { int jc = jieCheng(5); System.out.println(jc); } /* Define a method to calculate factorial, and the method calls itself */ public static int jieCheng(int n){//5,4,3,2,1 //Condition for the end of recursion: it ends when 1 is obtained if(n==1){ return 1; } //The purpose of recursion: get the next multiplied number n-1 return n * jieCheng(n-1); } }
5. Exercise: File Search
package com.itheima.demo02Recursion; import java.io.File; /* Exercise: File Search Simulate the file search function in windows system Search out the files at the end of all. java files in the d:\aaa directory, and print the absolute path of the file analysis: 1. Directory search, can not determine how many levels of directories, so use recursion to traverse all directories. 2. When traversing the directory, obtain the sub files, and judge whether they meet the recursion conditions through the file name. 3. If it is a directory, continue to traverse recursively, and it is the file at the end of the output. java of the file Steps: 1.Define a method getAllFile to traverse the directory according to the directory. The parameter passes the File object to traverse the directory 2.In the method, the directory to be traversed is passed according to the parameters, and the directory is traversed 3.Get the File object of each File folder 4.When judging that the File object is a File folder It is a file: judge whether the file ends in. java|.JAVA, and it is the absolute path to print the file Is a folder: continue traversing the folder We found that getAllFile is a method for traversing the directory. Just call the getAllFile method (recursion) */ public class Demo04Test { public static void main(String[] args) { File file = new File("d:\\aaa"); getAllFile(file); } /* 1.Define a method getAllFile to traverse the directory according to the directory. The parameter passes the File object to traverse the directory */ public static void getAllFile(File dir){ //2. In the method, pass the directory to be traversed according to the parameters and traverse the directory File[] files = dir.listFiles(); //Add a non null judgment to prevent null pointer exceptions if(files!=null && files.length>0){ //3. Get the File object of each File folder for (File f : files) { //4. Judge whether the File object is a File folder if(f.isFile()){ //It is a file: judge whether the file ends in. java|.JAVA, and it is the absolute path to print the file /* Convert File object to string String f.toString(); "D:\aaa\aaa.java" String f.getPath(); "D:\aaa\aaa.java" String f.getName(); "aaa.java" B.JAVA==>Lowercase = = > tolowercase() = = > "b.java" */ if(f.getName().toLowerCase().endsWith(".java")){ System.out.println(f.getAbsolutePath()); } }else{ //Is a folder: continue traversing the folder //We found that getAllFile is a method for traversing the directory. Just call the getAllFile method (recursion) getAllFile(f); } } } } }
Chapter III IO overview
1. Overview and classification of IO flow
2. Everything is a byte
All file data (text, picture, video, etc.) in the hard disk are stored in the form of binary numbers (the computer can only recognize 0 and 1), and are bytes one by one (1 byte = 8 bits), so it is the same when transmitting. Therefore, byte stream can transfer any file data. When operating a stream, we should always make it clear that no matter what kind of stream object is used, the underlying transmission is always binary data (1,0).
0,1 bit: the smallest unit of a computer
In order to facilitate the formation of eight zeros and ones into one byte: the basic unit of the computer
Chapter 4 byte stream
1. Introduction to byte output stream (understand)
java.io.OutputStream class:Byte output stream This abstract class is a superclass that represents all classes of the output byte stream. OutputStream Class is the parent class of all byte output streams,It defines the common member method of all byte output streams,Any subclass can be used OutputStream Class: public void close() : Close this output stream and free any system resources associated with this stream. public void flush() : Refresh this output stream and force any buffered output bytes to be written out. public void write(byte[] b) : take b.length Bytes writes to this output stream from the specified byte array. public void write(byte[] b, int off, int len) : Writes from the specified byte array len Bytes, Offset from off Start output to this output stream. public abstract void write(int b) : Outputs the specified bytes to the stream ------------------------------------------------------------------------------------- java.io.FileOutputStream:File byte output stream extends OutputStream:Byte output stream effect:Write the data in memory to the file in bytes Construction method: FileOutputStream(File file) establish FileOutputStream object FileOutputStream(String name) establish FileOutputStream object parameter:Transfer the destination of the written data d:\\1.txt File file:A destination is a file String name:The destination is the path to a file Function of construction method: 1.establish FileOutputStream object 2.The destination where the data is written according to the transfer,Create a related file 3.Will put FileOutputStream Object points to the created file ------------------------------------------------------------------------------------- java The program writes data from memory to the bottom of the hard disk: java program==>JVM==>operating system==>Call the method of writing data in the operating system==>Write data to a file
2. Basic use of byte output stream (key points)
package com.itheima.demo03OutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; /* Basic use of byte output stream (key) Use steps: 1.Create a file byte output stream FileOutputStream object, and bind the destination to be written in the construction method 2.Use the write method in the FileOutputStream object to write data to the file in bytes 3.Free resources (close this output stream and free any system resources associated with this stream) */ public class Demo01FileOutputStream { public static void main(String[] args) throws IOException { //1. Create a file byte output stream FileOutputStream object, and bind the destination to be written in the construction method //FileOutputStream fos = new FileOutputStream("e:\1.txt");//FileNotFoundException: e:.txt (the system cannot find the specified path.) FileOutputStream fos = new FileOutputStream("day10\\1.txt"); //2. Use the write method in the FileOutputStream object to write the data to the file in bytes //void write(int b) writes one byte at a time fos.write(97); //3. Release resources (close this output stream and release any system resources associated with this stream) fos.close(); } }
2. Open the file with Notepad to query the code table (extension - interview)
3. Method of writing multiple bytes in byte output stream (emphasis)
package com.itheima.demo03OutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; /* Method of writing multiple bytes in byte output stream (emphasis) void write(int b) Write one byte at a time void write(byte[] b) Write multiple bytes in the array at one time void write(byte[] b, int off, int len) Write some bytes in the array at a time int off:Array start index int len: number of writes */ public class Demo02FileOutputStream { public static void main(String[] args) throws IOException { //Requirements: write the three bytes 65, 66 and 67 into the file FileOutputStream fos = new FileOutputStream("day10\\2.txt"); //Write one byte at a time, three times //fos.write(65); //fos.write(66); //fos.write(67); byte[] bytes = {65,66,67}; //Write all the bytes in the array to the file at once fos.write(bytes); fos.close(); byte[] bytes2 = {Data of byte array,Documents in references}; FileOutputStream fos2 = new FileOutputStream("day10\\1.jpg"); //Write all bytes in the byte array to the file. Note that the suffix of the file is. jpg fos2.write(bytes2); fos2.close(); FileOutputStream fos3 = new FileOutputStream("day10\\2.jpg"); //Write some bytes in the byte array to the file. Note that the suffix of the file is. jpg fos3.write(bytes2,0,2000); fos3.close(); } }
4. Continuation and line feed of byte output stream (key)
package com.itheima.demo03OutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; /* Continue write: append write Construction method using two parameters: FileOutputStream(File file, boolean append) FileOutputStream(String name, boolean append) Parameters: File file|String name:Destination to write data boolean append:Append write switch true:Can continue writing (write data at the end of the previous file) false:Cannot continue writing (create a new blank file, overwrite the previous file with the same name, and write data in the new file) */ public class Demo03FileOutputStream { public static void main(String[] args) throws IOException { FileOutputStream fos = new FileOutputStream(new File("day10\\3.txt"),true); byte[] bytes = "Hello".getBytes(); fos.write(bytes); fos.close(); } }
package com.itheima.demo03OutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; /* Line breaks: using line breaks Windows In the system, the end of each line is carriage return + line feed, that is \ r\n; Unix In the system, there is only newline at the end of each line, that is \ n; Mac In the system, the end of each line is enter, that is \ r. Unified with Linux starting with Mac OS X. */ public class Demo04FileOutputStream { public static void main(String[] args) throws IOException { //Requirements: it is known that some data is stored in the set. We want to write the data in the set to the file and save each data in one line. How to achieve that? ArrayList<String> list = new ArrayList<>(); list.add("i love java!"); list.add("i need java!"); list.add("i miss java!"); FileOutputStream fos = new FileOutputStream("day10\\4.txt",true); //Traverse the collection to get each element for (String s : list) { fos.write(s.getBytes()); //Write a carriage return line feed symbol after each element is written fos.write("\r\n".getBytes()); } fos.close(); } }
5. Introduction to byte input stream (understand)
java.io.InputStream:Byte input stream This abstract class is a superclass representing all classes of byte input stream. InputStream Is the parent of all byte input streams,It defines the common member methods in all byte input streams,Any byte input stream can be used Common membership method: int read() Read one byte of the file at a time and return int read(byte[] b) Read multiple bytes in the file at one time and store them in the array void close() Close this input stream and release all system resources associated with the stream. java.io.FileInputStream:File byte input stream extends InputStream:Byte input stream effect:The data in the file can be,Read into memory in bytes Construction method: FileInputStream(File file) establish FileInputStream object FileInputStream(String name) establish FileInputStream object parameter:Pass the data source to read File file:A data source is a file String name:The data source is a file path Function of construction method: 1.establish FileInputStream object 2.Will create FileInputStream Object points to the first byte of the file to be read be careful:If a file is passed|The file path does not exist,Then creating a stream object will throw an exception that the file cannot be found use java The underlying process by which a program reads a file: java program==>JVM==>operating system==>Call the operating system to read the file==>Read data into memory
6. Basic use of byte input stream: read one byte at a time (key)
package com.itheima.demo04InputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; /* Basic use of byte input stream: read one byte at a time (key) int read() Read one byte of the file at a time and return Use steps: 1.Create a file byte input stream FileInputStream object, and bind the data source to be read in the construction method 2.Use the read method in the FileInputStream object to read the file in bytes 3.Release resources */ public class Demo01FileInputStream { public static void main(String[] args) throws IOException { //1. Create a file byte input stream FileInputStream object, and bind the data source to be read in the construction method FileInputStream fis = new FileInputStream("day10\\a.txt"); //2. Use the read method in the FileInputStream object to read the file in bytes /* We found that using the read method to read files is a repetitive process You can use a loop to simplify the read code. You don't know how many bytes there are in the file or how many times the loop needs to be cycled Use the while loop to the end condition of the loop, and the read method returns - 1 to end while Meaning of cyclic Boolean expression: (len = FIS. Read())=- one 1.fis.read() Read a byte in the file 2.len=fis.read() Assign the read bytes to the variable len 3.(len=fis.read())!=-1 Judge whether the variable len is - 1 If not - 1, execute the loop body and print len (read bytes) Yes - 1, end cycle */ int len = 0; while ((len=fis.read())!=-1){ System.out.print((char)len); } //3. Release resources fis.close(); } /* int len = fis.read(); System.out.println(len);//97 len = fis.read(); System.out.println(len);//98 len = fis.read(); System.out.println(len);//99 len = fis.read(); System.out.println(len);//-1 */ }
Key codes:
package com.itheima.demo04InputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; /* Basic use of byte input stream: read one byte at a time (key) int read() Read one byte of the file at a time and return Use steps: 1.Create a file byte input stream FileInputStream object, and bind the data source to be read in the construction method 2.Use the read method in the FileInputStream object to read the file in bytes 3.Release resources */ public class Demo01FileInputStream { public static void main(String[] args) throws IOException { //1. Create a file byte input stream FileInputStream object, and bind the data source to be read in the construction method FileInputStream fis = new FileInputStream("day10\\a.txt"); //2. Use the read method in the FileInputStream object to read the file in bytes int len = 0; while ((len=fis.read())!=-1){ System.out.print((char)len); } //3. Release resources fis.close(); } }
7. Use byte input stream to read multiple bytes at a time (key)
package com.itheima.demo04InputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Arrays; /* Use byte input stream to read multiple bytes at a time (key) int read(byte[] b) Read up to b.length bytes of data into a byte array from this input stream. Two things are clear: 1.What is the function of the parameter byte array byte [] of the method? Store multiple bytes read The appropriate length is 1024 or an integer multiple of 1024 1 Bytes = 8 bits (0,1) 1k=1024 byte 1M=1024k 1G=1024M 1T=1024G 1P=1024T 2.What is the return value int of the method? Number of valid bytes read each time Return - 1 after reading to the end String Class construction method: String(byte[] bytes) Convert byte array query encoding table to string String(byte[] bytes, int offset, int length) Convert a part of the byte array query encoding table into a string int offset:Start index int length: number of conversions */ public class Demo02FileInputStream { public static void main(String[] args) throws IOException { FileInputStream fis = new FileInputStream("day10\\b.txt"); /* We also found that using the read(byte []) method, reading files is also a repeated process You can use loop optimization. You don't know how many bytes there are in the file. Use the while loop while If the loop ends, read returns - 1 */ int len = 0; byte[] bytes = new byte[1024]; while ((len=fis.read(bytes))!=-1){ //System.out.println(Arrays.toString(bytes));//[65, 66, 67, 68, 69, 0, 0, 0, 0, 0, 0,...] //Convert the read valid bytes into a string System.out.println(new String(bytes,0,len)); } fis.close(); } /* byte[] bytes = new byte[2]; System.out.println(Arrays.toString(bytes));//[0, 0] int len = fis.read(bytes); System.out.println(len);//2 System.out.println(Arrays.toString(bytes));//[65, 66] System.out.println(new String(bytes));//AB len = fis.read(bytes); System.out.println(len);//2 System.out.println(new String(bytes));//CD len = fis.read(bytes); System.out.println(len);//1 System.out.println(new String(bytes));//ED len = fis.read(bytes); System.out.println(len);//-1 System.out.println(new String(bytes));//ED */ }
Key codes:
package com.itheima.demo04InputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Arrays; /* Use byte input stream to read multiple bytes at a time (key) int read(byte[] b) Read up to b.length bytes of data into a byte array from this input stream. Two things are clear: 1.What is the function of the parameter byte array byte [] of the method? Store multiple bytes read The appropriate length is 1024 or an integer multiple of 1024 1 Bytes = 8 bits (0,1) 1k=1024 byte 1M=1024k 1G=1024M 1T=1024G 1P=1024T 2.What is the return value int of the method? Number of valid bytes read each time Return - 1 after reading to the end String Class construction method: String(byte[] bytes) Convert byte array query encoding table to string String(byte[] bytes, int offset, int length) Convert a part of the byte array query encoding table into a string int offset:Start index int length: number of conversions */ public class Demo02FileInputStream { public static void main(String[] args) throws IOException { FileInputStream fis = new FileInputStream("day10\\b.txt"); int len = 0; byte[] bytes = new byte[1024]; while ((len=fis.read(bytes))!=-1){ //Convert the read valid bytes into a string System.out.println(new String(bytes,0,len)); } fis.close(); } }
package com.itheima.demo04InputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Arrays; /* Read pictures using byte input stream day10\\1.jpg 8,528 byte */ public class Demo03FileInputStream { public static void main(String[] args) throws IOException { FileInputStream fis = new FileInputStream("day10\\1.jpg"); byte[] bytes = new byte[8528]; int len = 0; while ((len=fis.read(bytes))!=-1){ System.out.println(Arrays.toString(bytes)); } fis.close(); } }
Note: do not import the package when using new String. The default first String is not the String in lang package
8. Document reproduction (key)
Principle:
Code implementation:
package com.itheima.demo05copyFile; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; /* File copying: one read and one write 1.Create a file byte input stream FileInputStream object, and bind the data source to be read in the construction method 2.Create a file byte output stream FileOutputStream object, and bind the destination to be written in the construction method 3.Use the read method in the FileInputStream object to read the file in bytes 4.Use the write method in the FileOutputStream object to write the read bytes to the destination 5.Release resources (first on and then off) */ public class Demo01CopyFile { public static void main(String[] args) throws IOException { long s = System.currentTimeMillis(); //copyFile01(); copyFile02(); long e = System.currentTimeMillis(); System.out.println("Total time taken to copy files:"+(e-s)+"millisecond"); } /* Use the byte input stream to read multiple bytes at a time, and use the byte output stream to write multiple bytes at a time to copy the file c:\\Global history.txt 4.91 MB (5155785 bytes) total time spent copying files: 65 milliseconds c:\\Origin. MP4 64.8 MB (67995218 bytes) total time taken to copy file: 974 milliseconds c:\\748m.rar 748 MB (785,042,177 Bytes) total time taken to copy files: 1537 MS */ private static void copyFile02() throws IOException { //1. Create a file byte input stream FileInputStream object, and bind the data source to be read in the construction method FileInputStream fis = new FileInputStream("c:\\748m.rar"); //2. Create a file byte output stream FileOutputStream object, and bind the destination to be written in the construction method FileOutputStream fos = new FileOutputStream("d:\\748m.rar"); //3. Use the read method in the FileInputStream object to read the file in bytes byte[] bytes = new byte[1024*500]; int len = 0; while ((len=fis.read(bytes))!=-1){ //4. Use the write method in the FileOutputStream object to write the read bytes to the destination fos.write(bytes,0,len);//The number of valid bytes read in each write is not necessarily 1024 in the last read } //5. Release resources (first on and then off) fos.close(); fis.close(); } /* Use the byte input stream to read one byte at a time, and use the byte output stream to write one byte at a time to copy the file c:\\1.jpg 157 KB (161,548 Bytes) total time taken to copy files: 1823 milliseconds c:\\Global history.txt 4.91 MB (5155785 bytes) total time spent copying files: 36184 milliseconds */ private static void copyFile01() throws IOException { //1. Create a file byte input stream FileInputStream object, and bind the data source to be read in the construction method FileInputStream fis = new FileInputStream("c:\\Global general history.txt"); //2. Create a file byte output stream FileOutputStream object, and bind the destination to be written in the construction method FileOutputStream fos = new FileOutputStream("d:\\Global general history.txt"); //3. Use the read method in the FileInputStream object to read the file in bytes int len = 0; while ((len=fis.read())!=-1){ //4. Use the write method in the FileOutputStream object to write the read bytes to the destination fos.write(len); } //5. Release resources (first on and then off) fos.close(); fis.close(); } }
Note: the parameters of the stream object can only be files, not folders
Experience sharing
1. Known file copy code
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class Test_File copy { public static void main(String[] args) throws IOException { //Create input stream FileInputStream fis = new FileInputStream("day13\\123.jpg"); //Create output stream FileOutputStream fos = new FileOutputStream("day13\\copy.jpg"); //Read multiple bytes at a time byte[] bytes = new byte[1024]; int len; while((len=fis.read(bytes)) != -1){ //Write out multiple bytes at a time fos.write(len); } //Closed flow fos.close(); fis.close(); } }
2. Problems
Size of source file "123.jpg":
Size of destination file copy. jpg:
3. Analysis of problems
The read() method reads 1024 bytes each time and stores them in the array. It returns the number of bytes actually read len (an integer).
In the write() output method, len is written, that is, an integer is output each time.
The source file has a total of 13465 bytes and needs to be read 14 times, so the above code is written into the file with 14 bytes. No actual read output
To the contents of the array, so the file copy error.
4. Solutions to problems
When outputting data, you should write:
fos.write(bytes,0,len);
Bytes stores the read byte contents. 0 represents the output from the 0 index of the array, and len represents the number of bytes output this time.
Summary:
Array is the container of bytes during file copying. When reading, read the bytes into the array and record the number of bytes read. When outputting, output the specified number of bytes in the array, and finally complete the file copying.