45-File Operation

File operations

  The Java language provides file operating system support, and this support is defined in the java.io.File class. It also means that in the entire java.io package, the File class is the only one that operates with the file itself ( Create, delete, rename, etc.) related classes. If you want to perform File class operations, you must provide a complete path before you can call the corresponding method for processing.

Basic operation of File class

  Open the JDK document and you can find that the File class is a subclass of the Comparable interface, so the objects of the File class can be sorted. When processing the File class, you need to set the access path for it, so the configuration of the path is mainly handled by the construction method of the File class.

  • Construction method:, public File(String pathname);set the full path of the file to be operated
  • Construction method:, public File(File parent,String child);set the parent path and subdirectory;

  Use the following methods to perform file operations:

  • Create a new file:public boolean createNewFile() throws IOException;
  • Determine whether the file exists:public boolean exists();
  • Delete Files:public boolean delete();

Create a file using the File class

import java.io.File;

public class File_Basic {
    
    

	public static void main(String[] args) throws Exception {
    
    
		  File file = new File("C:\\Project\\Java_study\\src\\文件\\test.txt");
		  if(file.exists()) {
    
    
			  file.delete();
			  System.out.println("文件已删除!");
		  }else {
    
    
			  file.createNewFile();		//创建新文件
			  System.out.println("已创建新文件!");
		  }
	}
}

  The File class implements the processing of the file itself.

File class operation in-depth

  Now that the basic operation of the file has been implemented, but there are also some problems with this operation, the following is optimized for the previous code.
  In the actual software project development and operation process, the project development is often carried out on Windows, and the project is released based on Linux or Unix during project deployment to ensure the security of the production environment;
  there are differences among different operating systems The path separator is Windows separator "\" and Linux separator is "/". At this time, the separator problem of different systems must be considered. In order to solve this problem, the File class provides a constant: public static final String separator;
normal path writing
File file = new File("C:"+File.separator+"Project"+File.separator+"Java_study"+File.separator+"src"+File.separator+"文件"+File.separator+"test.txt");
follows The adaptability of the system is continuously strengthened, and the current path operation can be used at will.

  When using the File class for file processing, you need to pay attention: Program -> JVM -> Operating System Function -> File Processing, so there may be a delay when the same file is repeatedly deleted or created, so the best solution at this time YesDon't repeat the name

  There is an important prerequisite when creating a file: the parent path of the file exists.

  • Get the parent path:public File getParentFile();
  • Create a directory:public boolean mkdir/mkdirs();
import java.io.File;
import java.io.IOException;

public class File_Inner {
    
    

	public static void main(String[] args) throws IOException {
    
    
		File file = new File("C:"+File.separator+"Project"+File.separator+"Java_study"+File.separator+"src"+File.separator+"文件"+File.separator+"test.txt");
		if(!file.getParentFile().exists()) {
    
    		//父路径不存在
			file.getParentFile().mkdirs();		//创建父路径
		}
		if(file.exists()) {
    
    
			file.delete();		//删除文件
		}else {
    
    
			file.createNewFile();		//创建新文件
		}
	}
}

This kind of judgment and the creation of the parent directory may only need to be done once in many cases, but if this judgment remains in the code consistently, it will increase the time complexity, so if you want to improve performance at this time, you must first ensure the directory Already created.

Get file information

  In addition to searching for files, you can also use the File class to get some information provided by the file itself. You can get the following:

  • Read/write/execute:public boolean canRead()/canWrite()/canExecute();
  • Get the file length:, public long length();the method returns the long data type, byte length.
  • Last modified date and time:public long lastModified();
  • Determine whether it is a directory/file:publio boolean isDirectory()/isFile();
  • List the contents of the directory:public File[] listFiles();
import java.io.File;
import java.text.SimpleDateFormat;

public class File_get {
    
    
	public static void main(String[] args) {
    
    
		File file = new File("C:\\Project\\Java_study\\src\\文件\\test.txt");
		System.out.println(file.canRead());
		System.out.println(file.canWrite());
		System.out.println(file.canExecute());
		System.out.println(file.length());
		System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file.lastModified()));
		System.out.println(file.isDirectory());
		System.out.println(file.isFile());
		File result [] = (new File("C:\\Project\\Java_study\\src").listFiles());
		for (int x = 0; x<result.length;x++) {
    
    
			System.out.println(result[x]);
		}
	}
}

  The information obtained is the operation of the file or the directory itself, and it does not involve the processing of the file content.

Comprehensive case: List all files in the specified directory

  Set a directory path arbitrarily, list all file information in the directory, including all files in subdirectories, and in such a processing situation, it can be done in a recursive manner.

import java.io.File;

public class Example_ls {
    
    

	public static void main(String[] args) {
    
    
		File file = new File("C:\\Project\\Java_study\\src");		//是一个目录
		listDir(file);
	}
	public static void listDir(File file) {
    
    
		if(file.isDirectory()) {
    
    
			File result[] = file.listFiles();		//列出目录中全部内容
			if(result!=null) {
    
    
				for(int x=0;x<result.length;x++) {
    
    
					listDir(result[x]);			//继续依次判断
				}
			}
			System.out.println(file);
		}
	}
}

Comprehensive case: file name change in batches

  Write the program, enter the directory name when the program is running, and change the suffix of all file names in the directory to .txt. For this type of operation, some assumptions must be set up. Files that can be renamed have a suffix. If there is no suffix, it is The additional suffix, if there is a suffix, the path must be intercepted with the last suffix.

import java.io.File;

public class Example_rename {
    
    

	public static void main(String[] args) {
    
    
		File file = new File("C:\\Project\\Java_study\\src\\文件");
		long start = System.currentTimeMillis();
		renameDir(file);
		long end = System.currentTimeMillis();
		System.out.println("Time:"+ (end-start));
	}
	public static void renameDir(File file) {
    
    
		if(file.isDirectory()) {
    
    		//is a Dir
			File result [] = file.listFiles();
			if(result != null) {
    
    
				for(int x =0;x<result.length;x++) {
    
    
					renameDir(result[x]);
				}
			}
		} else {
    
    
				if(file.isFile()) {
    
    		//is a File
					String fileName = null;
					if(file.getName().contains(".")) {
    
    
						fileName = file.getName().substring(0,file.getName().lastIndexOf("."))+".txt";
					} else {
    
    
						fileName = file.getName() + ".txt";
					}
					File newFile = new File(file.getParentFile(),fileName);		//新文件名称
					file.renameTo(newFile);
				}
			}
	}
}

  In the interview process, a path often appears and then allows you to modify the name or file in batches, just use the above structure.

Guess you like

Origin blog.csdn.net/MARVEL_3000/article/details/113029291