inotgo.com


Tool version compatibility problem
Files and folders are all in File On behalf of
Correct

This video is interpretive , So I hope you have read the content of this knowledge point , And after writing the corresponding code , Watch with questions , Only in this way can we gain more . It is not recommended to watch the video at the beginning



14 branch 55 second
This video uses html5 Play mode , If it cannot be played normally , Please upgrade your browser to the latest version , Recommend Firefox ,chrome,360 browser . If thunderbolt is installed , Play the video and show the direct download status , Please adjust Thunderbolt system settings - Basic settings - Start - Monitor all browsers ( Remove this option ). chrome of Video download Plug-in will affect playback , as IDM etc. , Please close or switch other browsers



Step 1 : Create a file object   
Step 2 : File common methods 1   
Step 3 : File common methods 2   
Step 4 : practice - traverse folder   
Step 5 : answer - traverse folder   
Step 6 : practice - Traverse subfolders   
Step 7 : answer - Traverse subfolders   

Use absolute path or relative path to create File Object
 Create a file object
package file; import java.io.File; public class TestFile { public static void main(String[] args) { // Absolute path File f1 = new File("d:/LOLFolder"); System.out.println("f1 The absolute path of :" + f1.getAbsolutePath()); // Relative path , Relative to working directory , If in eclipse In , Is the project directory File f2 = new File("LOL.exe"); System.out.println("f2 The absolute path of :" + f2.getAbsolutePath()); // hold f1 Create a file object as the parent directory File f3 = new File(f1, "LOL.exe"); System.out.println("f3 The absolute path of :" + f3.getAbsolutePath()); } }
package file;
 
import java.io.File;
 
public class TestFile {
 
    public static void main(String[] args) {
        //  Absolute path 
        File f1 = new File("d:/LOLFolder");
        System.out.println("f1 The absolute path of :" + f1.getAbsolutePath());
        //  Relative path , Relative to working directory , If in eclipse In , Is the project directory 
        File f2 = new File("LOL.exe");
        System.out.println("f2 The absolute path of :" + f2.getAbsolutePath());
 
        //  hold f1 Create a file object as the parent directory 
        File f3 = new File(f1, "LOL.exe");
 
        System.out.println("f3 The absolute path of :" + f3.getAbsolutePath());
    }
}
be careful 1: Need to be in D:\LOLFolder There is indeed a LOL.exe, Then you can see the corresponding file length 、 Modification time and other information

be careful 2: renameTo Method is used to modify the physical file name , But it will not change File Of the object name attribute .
 File common methods 1
package file; import java.io.File; import java.util.Date; public class TestFile { public static void main(String[] args) { File f = new File("d:/LOLFolder/LOL.exe"); System.out.println(" The current file is :" +f); // Whether the file exists System.out.println(" Determine whether there is :"+f.exists()); // Whether it is a folder System.out.println(" Determine whether it is a folder :"+f.isDirectory()); // Whether it is a file ( Non folder ) System.out.println(" Determine whether it is a file :"+f.isFile()); // File length System.out.println(" Get the length of the file :"+f.length()); // Last modification time of the file long time = f.lastModified(); Date d = new Date(time); System.out.println(" Gets the last modification time of the file :"+d); // Set the file modification time to 1970.1.1 08:00:00 f.setLastModified(0); // File rename File f2 =new File("d:/LOLFolder/DOTA.exe"); f.renameTo(f2); System.out.println(" hold LOL.exe Changed its name to DOTA.exe"); System.out.println(" be careful : Need to be in D:\\LOLFolder There is indeed a LOL.exe,\r\n Then you can see the corresponding file length 、 Modification time and other information "); } }
package file; import java.io.File; import java.io.IOException; public class TestFile { public static void main(String[] args) throws IOException { File f = new File("d:/LOLFolder/skin/garen.ski"); // In the form of a string array , Returns all files in the current folder ( Does not contain sub files and sub folders ) f.list(); // In the form of a file array , Returns all files in the current folder ( Does not contain sub files and sub folders ) File[]fs= f.listFiles(); // Returns the folder where the retrieval is located as a string f.getParent(); // Return to get the folder in the form of file f.getParentFile(); // Create folder , If the parent folder skin non-existent , Creation is invalid f.mkdir(); // Create folder , If the parent folder skin non-existent , The parent folder will be created f.mkdirs(); // Create an empty file , If the parent folder skin non-existent , Will throw an exception f.createNewFile(); // So before creating an empty file , The parent directory is usually created f.getParentFile().mkdirs(); // List all drive letters c: d: e: wait f.listRoots(); // Delete file f.delete(); // JVM At the end , Delete file , It is often used to delete temporary files f.deleteOnExit(); } }
Step 4 :

practice - traverse folder

edit top fracture   Wrong posture , get half the results with double the effort ! Click to see the correct posture for the exercise
Generally speaking, the operating system will be installed in C disc , So there will be one C:\WINDOWS catalogue .

Traverse all the files in this directory ( You don't have to traverse subdirectories )

Find these files , Maximum and minimum ( wrong 0) The file of , Print out their file names

notes : The smallest file cannot be 0 Length
 practice - traverse folder
Before looking at the answers , Try to finish it yourself first , See the answer when you encounter a problem , The harvest will be more
Before looking at the answers , Try to finish it yourself first , See the answer when you encounter a problem , The harvest will be more
Before looking at the answers , Try to finish it yourself first , See the answer when you encounter a problem , The harvest will be more
Viewing this answer will cost 3 Points , You currently have a total of Point integral . It doesn't cost extra points to see the same answer . Points increase method Or One time purchase JAVA Intermediate total 0 One answer ( Total required 0 Integral )
Viewing this answer will cost 3 Points , You currently have a total of Point integral . It doesn't cost extra points to see the same answer . Points increase method Or One time purchase JAVA Intermediate total 0 One answer ( Total required 0 Integral )
Account not activated Account not activated , Limited functionality . Please click activate
This video is interpretive , So I hope you have read the content of this answer , Watch with questions , Only in this way can we gain more . It is not recommended to watch the video at the beginning

3 branch 6 second This video uses html5 Play mode , If it cannot be played normally , Please upgrade your browser to the latest version , Recommend Firefox ,chrome,360 browser . If thunderbolt is installed , Play the video and show the direct download status , Please adjust Thunderbolt system settings - Basic settings - Start - Monitor all browsers ( Remove this option ). chrome of Video download Plug-in will affect playback , as IDM etc. , Please close or switch other browsers


package file; import java.io.File; public class TestFile { public static void main(String[] args) { File f = new File("c:\\windows"); File[] fs = f.listFiles(); if(null==fs) return; long minSize = Integer.MAX_VALUE; long maxSize = 0; File minFile = null; File maxFile = null; for (File file : fs) { if(file.isDirectory()) continue; if(file.length()>maxSize){ maxSize = file.length(); maxFile = file; } if(file.length()!=0 && file.length()<minSize){ minSize = file.length(); minFile = file; } } System.out.printf(" The biggest file is %s, Its size is %,d Bytes %n",maxFile.getAbsoluteFile(),maxFile.length()); System.out.printf(" The smallest file is %s, Its size is %,d Bytes %n",minFile.getAbsoluteFile(),minFile.length()); } }
Step 6 :

practice - Traverse subfolders

edit top fracture   Wrong posture , get half the results with double the effort ! Click to see the correct posture for the exercise
The same exercise , Require traversal of subfolders
Before looking at the answers , Try to finish it yourself first , See the answer when you encounter a problem , The harvest will be more
Before looking at the answers , Try to finish it yourself first , See the answer when you encounter a problem , The harvest will be more
Before looking at the answers , Try to finish it yourself first , See the answer when you encounter a problem , The harvest will be more
Viewing this answer will cost 5 Points , You currently have a total of Point integral . It doesn't cost extra points to see the same answer . Points increase method Or One time purchase JAVA Intermediate total 0 One answer ( Total required 0 Integral )
Viewing this answer will cost 5 Points , You currently have a total of Point integral . It doesn't cost extra points to see the same answer . Points increase method Or One time purchase JAVA Intermediate total 0 One answer ( Total required 0 Integral )
Account not activated Account not activated , Limited functionality . Please click activate
This video is interpretive , So I hope you have read the content of this answer , Watch with questions , Only in this way can we gain more . It is not recommended to watch the video at the beginning

3 branch 36 second This video uses html5 Play mode , If it cannot be played normally , Please upgrade your browser to the latest version , Recommend Firefox ,chrome,360 browser . If thunderbolt is installed , Play the video and show the direct download status , Please adjust Thunderbolt system settings - Basic settings - Start - Monitor all browsers ( Remove this option ). chrome of Video download Plug-in will affect playback , as IDM etc. , Please close or switch other browsers


Use recursion to traverse folders
package file; import java.io.File; public class TestFile { static long minSize = Integer.MAX_VALUE; static long maxSize = 0; static File minFile = null; static File maxFile = null; // Use recursion to traverse the sub files of a folder public static void listFiles(File file){ if(file.isFile()){ if(file.length()>maxSize){ maxSize = file.length(); maxFile = file; } if(file.length()!=0 && file.length()<minSize){ minSize = file.length(); minFile = file; } return; } if(file.isDirectory()){ File[] fs = file.listFiles(); if(null!=fs) for (File f : fs) { listFiles(f); } } } public static void main(String[] args) { File f = new File("c:\\windows"); listFiles(f); System.out.printf(" The biggest file is %s, Its size is %,d Bytes %n",maxFile.getAbsoluteFile(),maxFile.length()); System.out.printf(" The smallest file is %s, Its size is %,d Bytes %n",minFile.getAbsoluteFile(),minFile.length()); } }


The official account of programming , Follow and get the latest tutorials and promotions in real time , thank you .


Q & A area    
2021-11-03 Practice traversing subfolders
logiczqr




There are three ways It's troublesome to write
/**
		 Traverse all files 
		 Find these files , Maximum and minimum ( wrong 0) The file of , Print out their file names 
	 */
	public static void test1(List<File> files) {
		long maxSize = 0, minSize = Long.MAX_VALUE;
		File maxfile = null;
		File minfile = null;
		for(File f: files){
			if (f.length() > maxSize) {
				maxSize = f.length();
				maxfile = f;
			}
					
			if (f.length() != 0 && f.length() < minSize){
				minSize = f.length();				
				minfile = f;
			}
		}
		
		System.out.printf(" The biggest file is \t%s, Its size is \t%d%n", maxfile, maxSize);
		System.out.printf(" The smallest file is \t%s, Its size is \t%d", minfile, minSize);				
	}
	
	/**
	 *  Traverse the files under the folder and put them into the collection 
	 */
	public static void test2(File file, List<File> files) {
		File[] list = file.listFiles();
		for (File f : list) {
			if (f.isDirectory()){
				method(f, files);
			}else {
				files.add(f);
			}
		}
		test1(files);
	}
	
	/**
	 *  If it's a folder , Traverse and find the files and put them into the collection 
	 * @param file
	 */
	public static void method(File file, List<File> files) {
		File[] list = file.listFiles();
		for (File f : list) {
			if (f.isDirectory() && f.length() != 0) {
				method(f, files);
			}else if (f.isFile()) {
				files.add(f);				
			}
		}
	}
 
               





The answer has been submitted successfully , Auditing . Please My answer Check the answer record at , thank you
answer Or code please Fill in at least one , If you have a problem , Please ask again , Otherwise, the webmaster may not see





2021-09-06 answer : practice 1, practice 2
Old oil head




practice 1: Thinking - Use an array to receive files , Get the maximum and minimum values by sorting practice 2: Thinking - Judge files and folders , Print files directly ; Folder repeat the previous step
 practice 1: 
package com.how2j.io;

import java.io.File;
import java.util.ArrayList;

/**
 * @author ZachLgodNbb
 */
public class TestFile3 {
    /**
     *  practice :  Get the largest and smallest files in the file 
     * @param args
     */
    public static void main(String[] args) {
        File file = new File("C:\\Windows");
        // Receive files 
        ArrayList<File> newFile = new ArrayList<>();
        // obtain Windows All files under , Filter out folders 
        File[] files = file.listFiles();
        if (files != null) {
            for (File file1 : files){
                if (file1.isFile()){
                    newFile.add(file1);
                }
            }
        }
        // Sort by bubbling , Get the largest and smallest files 
        for(int i=0; i<newFile.size()-1;i++){
            for(int j=0;j<newFile.size()-1-i;j++){
                if(newFile.get(j).length() < newFile.get(j+1).length()){
                    File temp = newFile.get(j);
                    newFile.set(j,newFile.get(j+1));
                    newFile.set(j+1,temp);
                }
            }
        }
        System.out.println(" The biggest file is : "+newFile.get(0)+
                ", Its size is : "+newFile.get(0).length());
        System.out.println(" The biggest file is : "+newFile.get(newFile.size()-1)+
                ", Its size is : "+newFile.get(newFile.size()-1).length());
    }
}
-----------------------------------------------------------------------------------------------------
 practice 2:
package com.how2j.io;

import java.io.File;

/**
 * @author ZachLgodNbb
 */
public class TestFile4 {
    /**
     *  practice :  traverse folder  ( Include sub files )
     * @param file
     */
    public static void findAll(File file){
        // Determine whether the file exists 
        if (!file.exists()) {
            System.out.println(" File does not exist !");
        }
        // If it's a file , Print the address directly + File name 
        if (file.isFile()){
            System.out.println(file.getPath() +" "+ file.getName());
        }else {
            // If it's not a file , Then take the path , Get the file through the path , Traverse the file 
            File[] files =file.listFiles();
            if (files != null) {
                for (File f: files){
                    if (f == null){
                        break;
                    }else {
                        findAll(f);
                    }
                }
            }
        }
    }
    public static void main(String[] args) {
        // Use with care ...
        File file = new File("C:\\Windows");
        findAll(file);
    }
}


 
               


1 One answer

AdorkAble Xiao Qiang
Answer time :2021-10-19
The biggest file is C:\Windows\Installer\1148d7.msi, The file size is 413687808 Bytes The smallest file is C:\Windows\Boot\PCAT\bootnxt, The file size is 1 Bytes



The answer has been submitted successfully , Auditing . Please My answer Check the answer record at , thank you
answer Or code please Fill in at least one , If you have a problem , Please ask again , Otherwise, the webmaster may not see





2021-08-15 Recursively traverse folders
2021-07-12 When recursively traversing a file without permission, it will return a null value
2021-05-06 The answer to traversing subfolders


Too many questions , Page rendering is too slow , To speed up rendering , Only a few questions are displayed on this page at most . also 165 Previous questions , please Click to view

Please... Before asking questions land
The question has been submitted successfully , Auditing . Please My question Check the question record at , thank you
about JAVA Intermediate -I/O- File object Your questions

Try to provide Screenshot code and Abnormal information , Help to analyze and solve problems . You can also enter this station QQ Group communication : 496725845
Ask questions and try to provide complete code , Environment description , The more conducive to the recurrence of the problem , The faster your question can be answered .
Have questions about the code in the tutorial , Please provide which step , Which line is in doubt , This makes it easy to quickly locate the problem , Improve the speed at which questions are answered
In the thousands of questions that already exist , A considerable proportion , Because of the use of and webmaster Different versions of the development environment Resulting in , For example jdk, eclpise, idea, mysql,tomcat Wait, the version of the software is inconsistent .
Please use the same version as the webmaster , You can save yourself a lot of learning time . The webmaster sorted out the software versions used in teaching , It's all here , Convenient for everyone to download : /k/helloworld/helloworld-version/1718.html

Upload screenshot