“This is the third day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021.”
The File type
1. An overview of the
The java.io.File class is an abstract representation of the path names of files and directories. It is used for creating, searching for, and deleting files and directories.
2. Construction method
public File(String pathname)
: by putting the givenPathname stringConvert to abstract pathname to create a new File instance.public File(String parent, String child)
From:Parent path name character string and child path name character stringCreate a new File instance.public File(File parent, String child)
From:Parent abstract path name and child path name stringCreate a new File instance.
-
For example, the code is as follows:
// File pathname String pathname = "D://111.txt"; File file1 = new File(pathname); // File pathname String pathname2 = "D://111//222.txt"; File file2 = new File(pathname2); // Through the parent path and child path string String parent = "d://111"; String child = "222.txt"; File file3 = new File(parent, child); // Through the parent File object and child path string File parentDir = new File("d://111"); String child = "222.txt"; File file4 = new File(parentDir, child); Copy the code
Tip:
- A File object represents a File or directory that actually exists on the hard disk.
- The creation of File objects does not affect whether files or directories exist in this path.
3. Common methods
Methods to get functionality
-
Public String getAbsolutePath() : Returns the absolute pathname String for this File.
-
Public String getPath() : Converts this File to a pathname String.
-
Public String getName() : Returns the name of the File or directory represented by this File.
-
Public long Length () : Returns the length of the File represented by this File.
Method demonstration, the code is as follows:
public class FileGet { public static void main(String[] args) { File f = new File("d://aaa/bbb.java"); System.out.println("File absolute path :"+f.getAbsolutePath()); System.out.println("File construction path :"+f.getPath()); System.out.println("File Name :"+f.getName()); System.out.println("File length :"+f.length()+"Byte"); File f2 = new File("d:/aaa"); System.out.println("Directory absolute path :"+f2.getAbsolutePath()); System.out.println("Directory construction path :"+f2.getPath()); System.out.println("Directory name :"+f2.getName()); System.out.println("Directory length :"+f2.length()); }}Copy the code
Output result:
> API: length() indicates the length of the file. But the File object represents a directory, so the return value is not specified. ### Absolute and relative pathsCopy the code
- Absolute path: the path starting from the drive letter. This is a complete path.
- Relative path: Relative to the project directory path, this is a convenient path, often used in development.
public class FilePath {
public static void main(String[] args) {
// bbb. Java file on disk D
File f = new File("D:/bbb.java");
System.out.println(f.getAbsolutePath());
// The bbb.java file under the project
File f2 = new File("bbb.java"); System.out.println(f2.getAbsolutePath()); }}Copy the code
Output result:
A method for judging functionality
public boolean exists()
: Indicates whether the File or directory actually exists.public boolean isDirectory()
: Indicates whether the File is a directory.public boolean isFile()
: Indicates whether the File is a File.
Method demonstration, the code is as follows:
public class FileIs {
public static void main(String[] args) {
File f = new File("d:/aaa//bbb.java");
File f2 = new File("d:/aaa");
// Check whether it exists
System.out.println("D :/aaa//bbb.java exists :" + f.exists());
System.out.println("D :/aaa exists :" + f2.exists());
// Determine whether it is a file or a directory
System.out.println("D: / aaa file? :" + f2.isFile());
System.out.println("d:/aaa 目录?:"+ f2.isDirectory()); }}Copy the code
Output result:
A method to create a delete function
public boolean createNewFile()
: Creates a new empty file if and only if a file with that name does not already exist.public boolean delete()
: Deletes the files or directories represented by this File.public boolean mkdir()
: Creates the directory represented by this File.public boolean mkdirs()
: Creates the directories represented by this File, including any required but nonexistent parent directories.
Method demonstration, the code is as follows:
public class FileCreateDelete {
public static void main(String[] args) throws IOException {
// Create a file
File f = new File("aaa.txt");
System.out.println("Does it exist?"+f.exists()); // false
System.out.println("Create or not :"+f.createNewFile()); // true
System.out.println("Does it exist?"+f.exists()); // true
// Directory creation
File f2= new File("newDir");
System.out.println("Does it exist?"+f2.exists());// false
System.out.println("Create or not :"+f2.mkdir()); // true
System.out.println("Does it exist?"+f2.exists());// true
// Create a multi-level directory
File f3= new File("newDira\newDirb");
System.out.println(f3.mkdir());// false
File f4= new File("newDira\newDirb");
System.out.println(f4.mkdirs());// true
// Delete files
System.out.println(f.delete());// true
// Delete the directory
System.out.println(f2.delete());// true
System.out.println(f4.delete());// false}}Copy the code
If this File represents a directory, the directory must be empty before it can be deleted.
4. Directory traversal
public String[] list()
: Returns an array of strings representing all subfiles or directories in the File directory.
public File[] listFiles()
: Returns an array of files representing all the subfiles or directories in the File directory.
public class FileFor {
public static void main(String[] args) {
File dir = new File("D://java_code");
// Get the names of the files and folders in the current directory.
String[] names = dir.list();
for(String name : names){
System.out.println(name);
}
// Get the file and folder object in the current directory. Once you get the file object, you can get more information
File[] files = dir.listFiles();
for(File file : files) { System.out.println(file); }}}Copy the code
Tip:
The File object that calls the listFiles method must represent an actual directory, otherwise null is returned and cannot be traversed.
Practical practice
1. File search
Search. Java files in the D://aaa directory.
Analysis:
- Directory search, can not determine how many levels of directory, so use recursion, traverse all directories.
- When traversing a directory, determine whether the subfiles obtained meet requirements based on the file names.
Code implementation:
public class DiGuiDemo3 {
public static void main(String[] args) {
// Create a File object
File dir = new File("D:/aaa");
// Call the print directory method
printDir(dir);
}
public static void printDir(File dir) {
// Get subfiles and directories
File[] files = dir.listFiles();
// Loop print
for (File file : files) {
if (file.isFile()) {
// If yes, determine the file name and output the absolute path of the file
if (file.getName().endsWith(".java")) {
System.out.println("File name :"+ file.getAbsolutePath()); }}else {
// is the directory, continue to iterate, form recursionprintDir(file); }}}}Copy the code
2. Optimize file filters
Java.io.FileFilter is an interface that acts as a filter for File. Objects of this interface can be passed as arguments to the listFiles(FileFilter) class of File, and there is only one method in the interface.
Boolean Accept (File PathName) : Tests whether the pathname should be included in the current File directory, returns true if it is.
Analysis:
-
Interface as a parameter, need to pass the subclass object, override the methods. We chose the anonymous inner class approach, which is relatively simple.
-
Accept method, which takes File and represents all subfiles and subdirectories under the current File. Returns true if it is retained, false if it is filtered. Reservation Rules:
- Or a.Java file.
- Or a directory to continue traversing.
-
Through the filter, the array elements returned by listFiles(FileFilter), the subfile objects are qualified and can be printed directly.
Code implementation:
public class DiGuiDemo4 {
public static void main(String[] args) {
File dir = new File("D:/aaa");
printDir2(dir);
}
public static void printDir2(File dir) {
// Create a filter subclass object in an anonymous inner class
File[] files = dir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.getName().endsWith(".java")||pathname.isDirectory(); }});// Loop print
for (File file : files) {
if (file.isFile()) {
System.out.println("File name :" + file.getAbsolutePath());
} else{ printDir2(file); }}}}Copy the code
3. Optimize your thinking
Analysis: FileFilter is a one-method interface, so you can use lambda expressions shorthand.
Lambda formats:
() - > {}Copy the code
Code implementation:
public static void printDir3(File dir) {
// rewrite lambda
File[] files = dir.listFiles(f ->{
return f.getName().endsWith(".java") || f.isDirectory();
});
// Loop print
for (File file : files) {
if (file.isFile()) {
System.out.println("File name :" + file.getAbsolutePath());
} else{ printDir3(file); }}}Copy the code