1. Use of java.io.File class

1.1 Overview
• The File class and various streams in this chapter are defined under the java.io package.
• A File object represents a file or file directory (commonly known as a folder) that may exist in the hard disk or network, and has
nothing to do with the platform. (Experience that everything is an object)
• File can create, delete, and rename files and directories, but File cannot access the file content itself. If you need to
access the file content itself, you need to use an input/output stream.
– A File object can be passed as a parameter to the stream's constructor.
• To represent a real file or directory in a Java program, there must be a File object, but
a File object in a Java program may not have a real file or directory.

1.2 Constructor

public File(String pathname) :以 pathname 
为路径创建 File 对象,可以是
绝对路径或者相对路径,如果 pathname 是相对路径,
则默认的当前路径在系统属性user.dir 中存储。
public File(String parent, String child)
以 parent 为父路径,child 为子路径创建 File 对象。
public File(File parent, String child)
根据一个父 File 对象和子文件路径创建 File 对象

About the path:
• Absolute path: the path starting from the drive letter, which is a complete path.
• Relative path: relative to the path of the project directory, this is a convenient path, often used in development. > – In IDEA, the relative path of the file in main is relative to the "current project" – In IDEA, the relative path of the file in the unit test method is relative to the "current
module

Example:


package com.atguigu.file;
import java.io.File;
public class FileObjectTest {
    
    
 public static void main(String[] args) {
    
    
 // 文件路径名
 String pathname = "D:\\aaa.txt";
 File file1 = new File(pathname);
 // 文件路径名
 String pathname2 = "D:\\aaa\\bbb.txt";
 File file2 = new File(pathname2);
 // 通过父路径和子路径字符串
 String parent = "d:\\aaa";
 String child = "bbb.txt";
 File file3 = new File(parent, child);
 // 通过父级 File 对象和子路径字符串
 File parentDir = new File("d:\\aaa");
 String childFile = "bbb.txt";
 File file4 = new File(parentDir, childFile);
 }
 
 @Test
 public void test01() throws IOException{
    
    
 File f1 = new File("d:\\atguigu\\javase\\HelloIO.java"); //绝
对路径
 System.out.println("文件/目录的名称:" + f1.getName());
 System.out.println("文件/目录的构造路径名:" + f1.getPath());
 System.out.println("文件/目录的绝对路径名:" + f1.getAbsolutePa
th());
 System.out.println("文件/目录的父目录名:" + f1.getParent());
 }
 @Test
 public void test02()throws IOException{
    
    
 File f2 = new File("/HelloIO.java");//绝对路径,从根路径开始
 System.out.println("文件/目录的名称:" + f2.getName());
 System.out.println("文件/目录的构造路径名:" + f2.getPath());
 System.out.println("文件/目录的绝对路径名:" + f2.getAbsolutePa
th());
 System.out.println("文件/目录的父目录名:" + f2.getParent());
 }
 @Test
 public void test03() throws IOException {
    
    
 File f3 = new File("HelloIO.java");//相对路径
 System.out.println("user.dir =" + System.getProperty("user.di
r"));
 System.out.println("文件/目录的名称:" + f3.getName());
 System.out.println("文件/目录的构造路径名:" + f3.getPath());
 System.out.println("文件/目录的绝对路径名:" + f3.getAbsolutePa
th());
 System.out.println("文件/目录的父目录名:" + f3.getParent());
 }
 @Test
 public void test04() throws IOException{
    
    
 File f5 = new File("HelloIO.java");//相对路径
 System.out.println("user.dir =" + System.getProperty("user.di
r"));
 System.out.println("文件/目录的名称:" + f5.getName());
 System.out.println("文件/目录的构造路径名:" + f5.getPath());
 System.out.println("文件/目录的绝对路径名:" + f5.getAbsolutePa
th());
 System.out.println("文件/目录的父目录名:" + f5.getParent());
 }
}

Note:
8. Regardless of whether there is a file or directory under the path, it does not affect the creation of the File object.
9. The path separator of window uses "\", and "\" in Java program means escape character,
so "\" is needed to express path in Windows. Or you can use "/" directly
. Java programs support "/" as a platform-independent path separator. Or use
the constant value of File.separator directly. For example:
File file2 = new File(“d:” + File.separator + “atguigu” + File.separator
+ “info.txt”);
10. When the constructed path is an absolute path, then the results of getPath and getAbsolutePath are the
same
When the construction path is a relative path, then the path of getAbsolutePath =
the path of user.dir + construction path

1.3 Commonly used methods
1. Get basic information of files and directories
• public String getName(): get name
• public String getPath(): get path
• public String getAbsolutePath(): get absolute path
• public File getAbsoluteFile(): get absolute path representation The file
• public String getParent(): Get the upper-level file directory path. If not, return null
• public long length(): Get the length of the file (ie: the number of bytes). Could not get the length of the directory.
• public long lastModified() : Get the last modification time, in milliseconds.
If the file or directory represented by the File object exists, when the File object instance is initialized,
it will use the attribute information of the corresponding file or directory in the hard disk (for example, time, type, etc.) to
assign values ​​to the properties of the File object, otherwise, except for the path and name, other properties of the File object will
retain the default values
insert image description here

package com.atguigu.file;
import java.io.File;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
public class FileInfoMethod {
    
    
 public static void main(String[] args) {
    
    
 File f = new File("d:/aaa/bbb.txt");
 System.out.println("文件构造路径:"+f.getPath());
 System.out.println("文件名称:"+f.getName());
 System.out.println("文件长度:"+f.length()+"字节");
 System.out.println("文件最后修改时间:" + LocalDateTime.ofInsta
nt(Instant.ofEpochMilli(f.lastModified()),ZoneId.of("Asia/Shanghai
")));
 File f2 = new File("d:/aaa");
 System.out.println("目录构造路径:"+f2.getPath());
 System.out.println("目录名称:"+f2.getName());
 System.out.println("目录长度:"+f2.length()+"字节");
 System.out.println("文件最后修改时间:" + LocalDateTime.ofInsta
nt(Instant.ofEpochMilli(f.lastModified()),ZoneId.of("Asia/Shanghai
")));
 }
}
输出结果:
文件构造路径:d:\aaa\bbb.java
文件名称:bbb.java
文件长度:636 字节
文件最后修改时间:2022-07-23T22:01:32.065
目录构造路径:d:\aaa
目录名称:aaa
目录长度:4096 字节
文件最后修改时间:2022-07-23T22:01:32.065

2. List the next level of the directory
• public String[] list(): return a String array, representing all sub-files or directories in the File directory
. • public File[] listFiles() : returns a File array, representing all sub-files or directories
in the File directory

package com.atguigu.file;
import org.junit.Test;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
public class DirListFiles {
    
    
 @Test
 public void test01() {
    
    
 File dir = new File("d:/atguigu");
 String[] subs = dir.list();
 for (String sub : subs) {
    
    
 System.out.println(sub);
 }
 }
}

3. The renaming function of the File class
• public boolean renameTo(File dest): Rename the file to the specified file path.

4. Method of judging function
• public boolean exists() : Whether the file or directory represented by this File actually exists.
• public boolean isDirectory() : Whether this File represents a directory.
• public boolean isFile() : Whether this File represents a file.
• public boolean canRead(): determine whether it is readable
• public boolean canWrite(): determine whether it is writable
• public boolean isHidden(): determine whether it is hidden

Example:

package com.atguigu.file;
import java.io.File;
public class FileIs {
    
    
 public static void main(String[] args) {
    
    
 File f = new File("d:\\aaa\\bbb.java");
 File f2 = new File("d:\\aaa");
 // 判断是否存在
 System.out.println("d:\\aaa\\bbb.java 是否存在:"+f.exists());
 System.out.println("d:\\aaa 是否存在:"+f2.exists());
 // 判断是文件还是目录
 System.out.println("d:\\aaa 文件?:"+f2.isFile());
 System.out.println("d:\\aaa 目录?:"+f2.isDirectory());
 }
}

Output:
d:\aaa\bbb.java exists: true
d:\aaa exists: true
d:\aaa file?: false
d:\aaa directory?: true
If the file or directory does not exist, then exists() , isFile() and isDirectory() both return
true

5. Create and delete functions

public boolean createNewFile() :创建文件。若文件存在,则不创建,返回
falsepublic boolean mkdir() :创建文件目录。如果此文件目录存在,就不创建了。
如果此文件目录的上层目录不存在,也不创建。public boolean mkdirs() :创建文件目录。如果上层文件目录不存在,一并创
建。public boolean delete() :删除文件或者文件夹 删除注意事项:① Java 中的
删除不走回收站。② 要删除一个文件目录,请注意该文件目录内不能包含文件或者
文件目录。

Example:

package com.atguigu.file;
import java.io.File;
import java.io.IOException;
public class FileCreateDelete {
    
    
 public static void main(String[] args) throws IOException {
    
    
 // 文件的创建
 File f = new File("aaa.txt");
 System.out.println("aaa.txt 是否存在:"+f.exists());
 System.out.println("aaa.txt 是否创建:"+f.createNewFile());
 System.out.println("aaa.txt 是否存在:"+f.exists());
 // 目录的创建
 File f2= new File("newDir");
 System.out.println("newDir 是否存在:"+f2.exists());
 System.out.println("newDir 是否创建:"+f2.mkdir());
 System.out.println("newDir 是否存在:"+f2.exists());
 // 创建一级目录
 File f3= new File("newDira\\newDirb");
 System.out.println("newDira\\newDirb 创建:" + f3.mkdir());
 File f4= new File("newDir\\newDirb");
 System.out.println("newDir\\newDirb 创建:" + f4.mkdir());
 // 创建多级目录
 File f5= new File("newDira\\newDirb");
 System.out.println("newDira\\newDirb 创建:" + f5.mkdirs());
 // 文件的删除
 System.out.println("aaa.txt 删除:" + f.delete());
 // 目录的删除
 System.out.println("newDir 删除:" + f2.delete());
 System.out.println("newDir\\newDirb 删除:" + f4.delete());
 }
}

Running result:
Whether aaa.txt exists: false
Whether aaa.txt is created: true
Whether aaa.txt exists: true
Whether newDir exists: false
NewDir Whether it is created: true NewDir
exists: true
NewDira\newDirb Created: false
newDir\newDirb Created: true
newDira\newDirb Create: true
aaa.txt Delete: true
newDir Delete: false
newDir\newDirb Delete: true
Description in the API: delete method, if this File represents a directory, the directory must be empty to be
deleted

Guess you like

Origin blog.csdn.net/weixin_45817985/article/details/131210963