Java recursively traverse folders, examples, read and write txt files

(Java practice three 2 code check) recursively traverse the folder, write file operation, read file operation.

1. Traverse the folder code template

Recursively traverse the given folder, looking for the file with the specified file name. If there is such a file, the console outputs the number and path of the file.

import java.io.File;
public class lll {
    
    
	static File floder = new File("D:\\Demos\\EclipseDemo");   //文件夹路径 
	static String filename = "Test1.java";
	static int num = 0;
	public static void main(String[] args) {
    
    
		if(!floder.isDirectory())
		{
    
    
			System.out.print("请输入文件夹的正确路径");  
		}
		else{
    
    			
			File[]files = floder.listFiles();		
			for (File f:files) {
    
    		
				getFile(f,filename);        
			}				
		}
		if(num==0) {
    
    
			System.out.print("不存在"+filename+"文件"+"\r\n");
		}
		else{
    
    
			System.out.print(filename+"文件数量为:"+num+"\r\n");
		}
	}
	public static void getFile(File f,String str) {
    
    		 
		if(f.isDirectory()){
    
        //如果还存在子目录则继续读取
			File[]subfiles = f.listFiles();
			for(File fi:subfiles){
    
    
				getFile(fi,str);
			}
		}
		else{
    
    		
			if(f.getName().equals(str)) {
    
     
				System.out.print(f.getName()); 
				System.out.print("\n");  
				getData(f);
			}
		}
	}
	public static void getData(File f) {
    
    		
		num++;
		System.out.print(f.getPath()+"\n");  
	}
}

Output result:
Insert picture description here

Two, write txt file

Traverse the given folder recursively, looking for files with the specified file name and file type. As a result, the newly created txt file is written into the folder. The output result is the file name and number of the file of the given file type, and the path of the file with the given file name. The latter is tabbed in order to be conspicuous in the output result.

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class hhh {
    
    
	static File floder = new File("D:\\Demos\\EclipseDemo");   //文件夹路径  "C:\\Users\\Administrator\\Desktop\\test"
	static FileWriter fw = null;             //写文件 txt
	static String filename = "Test1.java";
	static String filetype = ".java";
	static int num1 = 0;
	static int num2 = 0;
	
	public static void main(String[] args) {
    
    
		try {
    
    
			fw = new FileWriter(floder.getPath() + "/" + "Summary.txt");   
			if(!floder.isDirectory())
			{
    
    
				System.out.print("请输入文件夹的正确路径");  
			}
			else{
    
    			
				File[]files = floder.listFiles();		
				for (File f:files) {
    
    		
					getFile(f,filename,filetype);        
				}				
			}	
			if(num1==0) {
    
    
				fw.write("不存在"+filename+"文件"+"\r\n");
			}
			else{
    
    
				fw.write(filename+"文件数量为:"+num1+"\r\n");
			}
		
			if(num2==0) {
    
    
				fw.write("不存在"+filetype+"类型文件"+"\r\n");
			}
			else{
    
    
				fw.write(filetype+"文件数量为:"+num2);
			}			
			fw.flush();
	   		fw.close();    		  		
		}catch (Exception e) {
    
    
	    	e.printStackTrace();
	    }		
	}
	public static void getFile(File f,String str,String str2) {
    
    		 
		if(f.isDirectory()){
    
        //如果还存在子目录则继续读取
			File[]subfiles = f.listFiles();
			for(File fi:subfiles){
    
    
				getFile(fi,str,str2);
			}
		}
		else{
    
    		
			if(f.getName().equals(str)) {
    
      
				System.out.print(f.getName()); 
				System.out.print("\n");  
				getData(f);
			}					
			if(f.getName().indexOf(str2)>0 ) {
    
      
				System.out.print(f.getName()); 
				System.out.print("\n");  
				getData2(f);
			}
		}
	}
	public static void getData(File f) {
    
    		
		try {
    
    
			fw.write("\r\t"+f.getName()+" : ");
			fw.write(f.getPath().substring(floder.getPath().length()+1)+"\r\n");
		} catch (IOException e) {
    
    
			e.printStackTrace();
		}
		num1++;
	}	
	public static void getData2(File f) {
    
    		
		num2++;	
		try{
    
    
			fw.write(f.getName());
			fw.write("\r\n");
		}catch (Exception e) {
    
    
    		e.printStackTrace();
    	}	
	}
}

Output result:
Insert picture description here
Insert picture description here

Three, read the txt file

Count the number of words in Litun's novels in the folder with subfolders
Insert picture description here

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class WordCount {
    
    
	static FileWriter fw = null;
	
	public static void main(String[] args)throws FileNotFoundException,IOException {
    
    
		File f = new File("D:\\All\\novel");    //          C:\\Users\\Administrator\\Desktop\\test
		fw = new FileWriter(f.getPath() + "/" + "字数统计.txt");  
		fw.write("文件名" + "\t\t\t"+"总字数" + "\t" + "汉字加标点"+ "\t" +"\r\n");		
		System.out.print("统计中"+"\r\n");  
		getFile(f,".txt");	
		fw.flush();
	   	fw.close();
	   	System.out.print("统计结束");  
	}

	public static void getFile(File f,String str)throws FileNotFoundException,IOException  {
    
    		 
		if(f.isDirectory()){
    
        //如果还存在子目录则继续读取
			File[]subfiles = f.listFiles();
			for(File fi:subfiles){
    
    
				getFile(fi,str);
			}
		}
		else{
    
    		
			if(f.getName().indexOf(str)>0) {
    
      
				CountNum(f);
			}				
		}
	}
		
	static int num = 0;
	public static void CountNum(File f)throws FileNotFoundException,IOException {
    
    
		num++;
		System.out.print("统计第"+num+"个文件"+"\r\n");  
		BufferedReader br = null;
		br = new BufferedReader(new FileReader(f));
		String tempstr; //临时字符串
		int num1 = 0; 	//总汉字数
		int num2 = 0; 	//汉字+标点	
		Pattern pattern =  Pattern.compile("([\u4e00-\u9fa5]{1})"); //纯汉字
		Pattern pattern2 = Pattern.compile("([\u4e00-\u9fa5,,.。、/<>??;;'‘’“”:\"【】{}]{1})"); // 汉字或标点符号   这样双引号算两个标点了		
		while((tempstr = br.readLine()) != null && tempstr != ""){
    
    
			//汉字
			Matcher matcher = pattern.matcher(tempstr);
			while(matcher.find()) num1++;	
			//汉字加标点
			Matcher matcher2 = pattern2.matcher(tempstr);
			while(matcher2.find()) num2++;

			tempstr = "";
		}			
		br.close();		
		fw.write(f.getName()+"\t"+num1+"\t"+num2+"\t"+"\r\n");
	}
}

Insert picture description here
Insert picture description here
It doesn't seem to be practical yet.
The problem found later is that the folder does not seem to be closed.

Guess you like

Origin blog.csdn.net/qq_43144103/article/details/107292685