[Java] Take you in-depth understanding of Java file operations: File class

Table of contents

1. What is the File class

2. Common operations of the File class

1. Create a File instance

2. The get method in File

3. Renaming of files or folders

4. Determine whether the current file or folder exists

5. Determine whether the file (folder) is readable and writable

6. Determine whether the current object is a file or a folder

7. Get the length of a file or folder

8. Creation and deletion of files (folders)

9. Get all directory names under the current folder

3. Comprehensive actual combat: get the names of all files or folders in the specified directory

4. All codes


1. What is the File class

        The Java file class represents filenames and directory pathnames in an abstract manner. This class is mainly used for creating files and directories, finding files and deleting files, etc. The File class is in the java.io package.
        It is easy to understand that a file refers to a file or folder . It is needed to create and delete files and folders. You can get various information about the file through it, but you cannot get the content of the file! ! To get the content of the file need to use other classes.

2. Common operations of the File class

1. Create a File instance

File has a total of 4 construction methods, all of which can be used to create objects. Here we only introduce the simplest and most commonly used one.

Directly enter the path of the file directory in the brackets. The path of the first line is a relative path, and the file name can be written directly, but the file should be placed in the folder of the project, otherwise the file cannot be found; the second line is an absolute path , that is, no matter where the file is placed, it can be found. At this time, f or f1 refers to the file corresponding to the path.

Note: In Java, '\' is an escape character, use \\ or / to represent the file separator

2. The get method in File

There are many get methods in the File class, but the final result returned is the name or path of the file (folder), so let's take a peek:

(1) getName(): This method is used to get the current file name or directory name (folder name)

(2) getPath(): Get the path of the current file or folder, which is the path filled in the new file

(3) getAbsolutePath(): Get the absolute path of the current file or folder

(4) getParent(): Obtain the parent path of the current file acquisition folder, that is, the path of its upper level folder

Specific examples are as follows:

 From the results, we can see that the return value is empty when obtaining the parent path of f. This is because we did not fill in the absolute path when we entered the new file. The system cannot find its parent path, so it returns null.

3. Renaming of files or folders

When renaming a file or folder we use the renameTo() method.

As shown in the figure below, there is a txt file named text under our folder, rename it to t, the operation is as follows:

We can observe its before and after changes 

4. Determine whether the current file or folder exists

We use the exists() method to determine whether the current file or folder exists, and return true if it exists, and false if it does not exist.

Here, since we renamed the text.txt file before, it does not exist now, so it returns false.

 

5. Determine whether the file (folder) is readable and writable

Due to the setting of certain file permissions, if we need to operate the file content, we must first determine whether the file is readable or writable, so as to avoid program exceptions caused by reading or writing failures in advance.

Use canRead() to judge whether it is readable; use canWrite() to judge whether it is writable.

 

 It can be seen here that the file can be read and written. When we modify its permissions in the file properties, the output is as follows:

6. Determine whether the current object is a file or a folder

Determine whether it is a file: isFile()

Determine whether it is a folder: isDirectory()

7. Get the length of a file or folder

The length() method can obtain the length of the current object in bytes, for example, to obtain the length of a text file:

 

 

8. Creation and deletion of files (folders)

 Both file and folder deletion use the delete() method, as follows:

 

Create a file with createNewFile(); create a single-level folder with mkdir(); create a multi-level folder with mkdirs().

As follows: Determine whether a file exists, and create it if it does not exist

 

 

Create a single-level directory and a multi-layer directory respectively. The single-level directory is named A, and the multi-layer directory is named B\C\D

 

 

 

9. Get all directory names under the current folder

Using the list() method, we can get the names of all folders and files under the current folder, but we can only go past this level, and we cannot get the contents of the folders under the folder directory in depth.

Just now we created a B folder, under which there is a C folder, we then manually create a text1.txt file, and use this method to get it.

 

3. Comprehensive actual combat: get the names of all files or folders in the specified directory

We choose to know that the list() method can obtain the names of all files and folders in the current directory, but cannot obtain the contents of the folders under the folder, so we need to design an algorithm to obtain the names of all files and folders in the specified directory name and output its absolute path, no matter how deep the hierarchy is.

Algorithm thinking:

First of all, we need to determine whether the current directory is a file or a folder. If it is a file, no operation is performed. If it is a folder, the name of the directory under the folder is obtained, and then these directories are judged. Repeated iterations until the last layer .

Since we have created a multi-layer directory like B\\C\\D before, and added the text1.txt file under the B-level folder, we will randomly create some files and folders for experimental verification.

 

 

 

	/*
	 * 练习:遍历某个目录下的所有文件,无论层级多深
	 * 需要用递归
	 * 主要方法如下
	 */
	
	public void traverse(File file){
		if(file.isFile()) {
			System.out.println("File:"+file.getAbsolutePath());
		}else {
			System.out.println("Folder:"+file.getAbsolutePath());
			File[] f = file.listFiles();
			if(f != null && f.length > 0) {
				for(File fs : f) {
					traverse(fs);
				}
			}
		}
	}

4. All codes

package io_lx;
/*
 * File只能操作文件本身:新建、删除、重命名文件和目录
 * 但是不能操作文件内容,如果需要,则要使用输入输出流
 */
import java.io.File;
import java.io.IOException;

public class File_lx {
	public static void main(String[] args) {
		//此时对象f就是text.txt文件
		//在Java中‘\’是转义符,用\\或/表示文件的分隔符
		File f = new File("text.txt");
		File f1 = new File("D:/JavaProgram/Study");
		
		System.out.println(f.getName());//获取当前文件名
		System.out.println(f1.getName());//获取当前目录名
		System.out.println("----------------------");
		System.out.println(f.getPath());//获取文件或文件夹路径,就是new file的路径
		System.out.println(f1.getPath());
		System.out.println("----------------------");
		System.out.println(f.getAbsolutePath());//获取当前文件的绝对路径
		System.out.println(f1.getAbsolutePath());
		System.out.println("----------------------");
		System.out.println(f.getParent());//返回当前文件或文件夹的父级路径
		System.out.println(f1.getParent());
		 
		//f.renameTo(new File("text.txt"));//文件或文件夹重命名
		
		File f2 = new File("text.txt");
		System.out.println(f2.exists());//文件或文件夹是否存在
		System.out.println(f.canWrite());//是否可写
		System.out.println(f.canRead());//是否可读
		System.out.println(f1.isFile());//判断当前file对象是否是文件
		System.out.println(f1.isDirectory());//判断当前file对象是否是文件夹
		
		System.out.println(f1.lastModified());//获取文件最后修改时间,返回一个毫秒数
		System.out.println(f.length());//返回文件(夹)长度,单位是字节
		
		//判断文件是否存在,不存在就创建一个
		File f3 = new File("text1.txt");
		System.out.println(f3.exists());
		if(!f3.exists()) {
			try {
				f3.createNewFile();//创建文件
			} catch (IOException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
		}
		File ff = new File("text.txt");
		System.out.println(ff.exists());
		ff.delete();//删除文件
		System.out.println(ff.exists());
		
		File f4 = new File("A");
		f4.mkdir();//创建单层目录,用此方法创建多层目录需要一层一层创建
		
		File f5 = new File("B\\C\\D");
		f5.mkdirs();//创建多级目录
		
		File f6 = new File("B");//返回当前文件夹子集的名称
		String[] s = f6.list();
		for(String s1 : s) {
			System.out.println(s1);
		}
		
		/*
		 * 练习:遍历某个目录下的所有文件,无论层级多深
		 * 需要用递归
		 */
		File f7 = new File("B");
		new File_lx().traverse(f7);
		
	}
	
	/*
	 * 练习:遍历某个目录下的所有文件,无论层级多深
	 * 需要用递归
	 * 主要方法如下
	 */
	
	public void traverse(File file){
		if(file.isFile()) {
			System.out.println("File:"+file.getAbsolutePath());
		}else {
			System.out.println("Folder:"+file.getAbsolutePath());
			File[] f = file.listFiles();
			if(f != null && f.length > 0) {
				for(File fs : f) {
					traverse(fs);
				}
			}
		}
	}
}

 

Guess you like

Origin blog.csdn.net/weixin_53972936/article/details/123487223