Educoder/Touge JAVA——JAVA object-oriented: file class

Level 1: Create a file

related tasks

how to create the file

We know that Javaeverything in Java is an object, so what is used to manipulate files should also be an object, which is a class, and classes are used to manipulate files Filein Java .File

How to create a file? Very simple, let's look at an example:

Use the above code to Dcreate a file under the disk helloworld.txt.

How to tell if a file exists

If a file already exists, then we generally should not create it, so we need to know whether the file exists, how to judge?

Run the above code, if it D://helloworld.txtalready exists, it will output true, otherwise it will output false;

programming requirements

Begin - EndPlease read the code on the right carefully, and supplement the code in the area according to the prompts in the method . The specific tasks are as follows:

  • src/outputCreated under the directory , hello.txtfile test.txt.

It needs to be created first test.txtand created later hello.txt.

Note: File operations have exceptions that need to be thrown.

Tips: The representation of the file directory in the windows system is D://XX.XX, and the representation of the file directory in Linux is /xxdir/filename.txt. The Linux environment is used in the platform, so the code should be written It is time to use the Linux directory method.

package step1;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.Scanner;

public class Task {
	/********* Begin *********/
	public void solution(){
        try{
            File file=new File("src/output/test.txt");
            if(file.exists()==false){
                file.createNewFile();
                //System.out.println("Success!");
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        try{
            File file=new File("src/output/hello.txt");
            if(file.exists()==false){
                file.createNewFile();
                //System.out.println("Success!");
            }
        }catch (IOException e){
            e.printStackTrace();
        }		
		/********* End *********/
	}
}

Level 2: Common operations on files

related information

create folder

This code will Dcreate a hellofolder under the disk.

Delete Files

This code can delete the file Dunder the diskhelloworld.txt

List files in a folder

If we want to develop a file viewer, then we need to be able to view all files in the specified folder; Javathis method is provided in .

Example:

DThe files under the disk hellofolder are as follows:

Write the following code:

Output result:

a.txt b.txt text.txt

It can be found that Javathe folder in the folder is also an Fileobject. listFiles()The method can be used to obtain the array of all files in the folder, and getName()the method can be used to obtain the file name of the file.

programming requirements

Begin - EndPlease read the code on the right carefully, and supplement the code in the area according to the prompts in the method to list all file information under the folder, delete the specified folder, and create a file under the folder. The specific requirements are as follows :

  • src/Create folder test2folder under;

  • Delete the file src/output/under test2.txt;

  • src/test2/Create helloworld.txtfiles and files under the directory step2.txt;

  • Sort src/output/the directory and src/test2/the file names of all files under the directory in ascending order and print to the console.

  • Tip: You can use the Arrays.sort() function to sort, and you need to import the methods in the Arrays class: import java.util.Arrays.

    package step2;
    
    import java.io.File;
    import java.io.FileFilter;
    import java.io.IOException;
    import java.util.Arrays;
    
    
    public class Task {
    	public static void dcFile() throws IOException {
    		/********* Begin *********/
    		File file1=new File("src/test2");
            file1.mkdir();
    
            File filed=new File("src/output/test2.txt");
            filed.delete();
    
            File file2=new File("src/test2/helloworld.txt");
            file2.createNewFile();
            File file3=new File("src/test2/step2.txt");
            file3.createNewFile();
    		
    		System.out.println("output目录结构为:");
            File dir1=new File("src/output");
            File[]files1=dir1.listFiles();
            String []n1=new String[5];
            int i=0;
            for(File file:files1){
                n1[i++]=file.getName();
                //System.out.println(n1[i-1]);
            }
            Arrays.sort(n1);
            for(int num1=0;num1<i;num1++){
                System.out.println(n1[num1]);
            }
    		System.out.println("test2目录结构为:");
            File dir2=new File("src/test2");
            File[]files2=dir2.listFiles();
            for(File file:files2){
                System.out.println(file.getName());
            }
    		/********* End *********/
    	}
    }

Level 3: File Viewer

related information

isDirectory()Methods can be used to determine Filewhether an object is a folder.

Example:

If D://helloit is a folder, output it true.

programming requirements

Begin - EndPlease read the code on the right carefully, and supplement the code in the area according to the prompts in the method . The specific tasks are as follows:

  • Realize the display of the directory structure of the given folder, and print to the console in the form of file names sorted in ascending order . If it is a folder, add it before its name +--, and if it is a file, add it --. The upper-level directory and the lower-level directory, and the lower-level file are separated by two spaces , and the functions in the code area on the right are supplemented showDirStructure(File dir)to achieve the required functions. Among them, the function parameters The meaning is as follows:

1). dir: Specify the folder to be displayed.

Note : mainFor functions, you can click the folder in the upper right corner to switch to Test.javathe file of this level for viewing.

package step3;

import java.io.File;
import java.util.Arrays;

public class Task {
	/********** Begin **********/
	int n=1;  //缩进层数
	public void showDirStructure(File file)	{
		System.out.println("+--"+file.getName());
		File[] dir = file.listFiles();
		Arrays.sort(dir);   // 按字母顺序给文件名排序
		for(File files:dir)
		{
			if(files.isDirectory())
			{
			for(int i=0;i<n*2;++i) System.out.print(" ");
				++n;    //是文件夹,缩进2个空格
				showDirStructure(files);
				--n;     //递归完成后返回上一层缩进。
			}
			else
			{
				for(int i=0;i<n*2;++i) System.out.print(" ");
				System.out.println("--"+files.getName());
			}
		}
}
	/********** End **********/    
}

Level 4: Image Viewer

related information

file filter

.SYSTo exclude all files with extension from the list , we can FileFilterdo so using a file filter represented by an instance of the functional interface.

It contains a accept()method which will Filetake list as argument and return if the file should be listed true. returns falsewill not list the files.

The following code creates a file filter that will filter .SYSfiles with the extension .

  1. FileFilter filter = file -> {
  2. if (file.isFile()) {
  3. String fileName = file.getName().toLowerCase();
  4. if (fileName.endsWith(".sys")) {
  5. return false;
  6. }
  7. }
  8. return true;
  9. };

The following code shows how to use a filter:

  1. import java.io.File;
  2. import java.io.FileFilter;
  3. public class Main {
  4. public static void main(String[] args) {
  5. String dirPath = "C:\\";
  6. File dir = new File(dirPath);
  7. // Create a file filter to exclude any .SYS file
  8. FileFilter filter = file -> {
  9. if (file.isFile()) {
  10. String fileName = file.getName().toLowerCase();
  11. if (fileName.endsWith(".sys")) {
  12. return false;
  13. }
  14. }
  15. return true;
  16. };
  17. File[] list = dir.listFiles(filter);
  18. for (File f : list) {
  19. if (f.isFile()) {
  20. System.out.println(f.getPath() + " (File)");
  21. } else if (f.isDirectory()) {
  22. System.out.println(f.getPath() + " (Directory)");
  23. }
  24. }
  25. }
  26. }

File Directory:

File directory printed after filtering:

programming requirements

Begin - EndPlease read the code on the right carefully, and supplement the code in the area according to the prompts in the method . The specific tasks are as follows:

  • Realize the display of the directory structure of the given folder, and print to the console in the form of file names sorted in ascending order. If it is a folder, add it before its name +--, and if it is a file, add it --. The upper-level directory and the lower-level directory, and the lower-level files are separated by two spaces . In addition, the files need to be filtered to only display files of image type. This level requires The image file types to be filtered are: “jpg,png,bmp”, please complete showDirStructure(File file)the functions in the code area on the right to realize the functions required by this level, and the meanings of the function parameters are as follows:

file: Specifies the folder to display.

package step4;

import java.io.File;
import java.io.FileFilter;
import java.util.Arrays;
public class Task {
	
	/********** Begin **********/
   public void showDirStructure(File file)	{
		if(file.isDirectory()){
			System.out.println("+--"+file.getName());
		}
		int Blank = 2;
		showDir(file,Blank);
	}
	public static void showDir(File file,int Blank){	
		File[] files = file.listFiles();
		Arrays.sort(files);
		for (int i = 0; i < files.length; i++) {
			if (files[i].isDirectory()) {
				for (int k = 0; k < Blank; k++) {
					System.out.print(" ");
				}
				System.out.println("+--" + files[i].getName());
				showDir(files[i], Blank+2);
			} 
			else {
				int end =  files[i].toString().indexOf(".");
				String suffix = files[i].toString().substring(end+1);
				if(suffix.equals("jpg") || suffix.equals("png") || suffix.equals("bmp")) {
					for (int k = 0; k < Blank; k++) {
						System.out.print(" ");
					}
					System.out.println("--" + files[i].getName());
				}
			}
		}
	}
	/********** End **********/    
}

Guess you like

Origin blog.csdn.net/zhou2622/article/details/128360091