Count all java files in a certain path, and count the number of codes

Reprinted from: https://blog.csdn.net/u012246342/article/details/51734358

 

This is an interview question my buddy encountered.

It is required to count the number of all Java files under a certain folder, and to count the number of codes.

In Java files, all gazes start with //, no /**/, and blank lines are not counted in the code count.

 

There are several difficulties in this interview question.

1. Traverse the folder, because there may be folders under the folder.

2. Read the file, judge code lines, comment lines, and blank lines.

3. Write the file.

 

In fact, the main thing is the operation of the file.

The code can be copied and run directly, the code is as follows:

package com;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;

public class ErgodicFiles {
	/*
	 *The following are all IO
	 *Let's talk a little here, byte stream character stream,
	 *Bytes consist of 8 binary bits. Anything stored in the computer is stored in binary bits. Therefore, any file can be stored with byte streams.
	 *byte stream, InputStream, OutputStream
	 * However, if you clearly know that this file belongs to a text file, and it is possible to operate on this text, read lines, write lines, etc., when performing line-level operations, use character streams.
	 *Character stream Reader, Writer
	 *
	 *Research on NIO,
	 * IO: Flow
	 *NIO: buffer
	 */
	static List<File> javalsf = new ArrayList<File>();
	static List<File> lsf = new ArrayList<File>();
	static int javaFileLinenum = 0;
	
	TreeSet<String> nums = new TreeSet<String>();
	
	public static void main(String[] args) throws Exception {
		
		File fir = new File("W:/test");
		FileOutputStream fio = null;
		try {
			//1、
			//byte stream input file
			getJavaFiles(fir,lsf);
			fio = new FileOutputStream(new File("W:/ALLFILE.txt"));
			String javastr = "The number of java files is: "+javalsf.size()+"pieces";
			String str = "The number of other files is: "+lsf.size()+"";
			// input to the file.
			fio.write(javastr.getBytes());
			
			//FileOutputStream 换行
			fio.write("\r\n".getBytes());
			
			// continue to output the file
			fio.write(str.getBytes());

			fio.write("\r\n".getBytes());
			fio.write("\r\n".getBytes());
			if(javalsf.size()>0){
				for(File javafir : javalsf){
					getJavaFileNum(javafir);
				}
			}
			String numstr = "The number of lines of java code is: "+javaFileLinenum;
			fio.write(numstr.getBytes());
			
			//2、
			// character stream input file
			//FileWriter fw = new FileWriter("w:/zfAllFile.txt");
			
			
		} catch (Exception e) {
			e.printStackTrace ();
		}finally{
			if(fio!=null){
				fio.close();
			}
		}
	}
	
	
	// Loop through all files in the path.
	public static List<File> getJavaFiles (File fir, List<File> listfile){
		
		//Check if the file exists
		 if (!fir.exists()){
	            System.out.println("File name does not exist!");
	        }else{
	        	// Determine if it is a file
	            if (fir.isFile()){
	            	//If the current fir is a file, determine what file it is
	            	String firName = fir.getName();//Get the file name
	            	
	            	//System.err.println(firName.hashCode()); Get the file suffix
	            	if(firName.substring(firName.lastIndexOf(".")+1) .equals("java")){
	            		javalsf.add(fir);
	            	}else{
	            		lsf.add(fir);
	            	}
	            } else{
	            	//If the current fir is a folder, traverse the entire folder as a File array, and continue to loop through
	            	File[] files = fir.listFiles();
	                for (int i = 0; i < files.length; i++  ){
	                	getJavaFiles(files[i], listfile);
	                }
	            }
	        }
		
		return lsf;
	}
	
	//View the number of codes in the java file
	public static void getJavaFileNum(File fir){
		int num = 0 ;
		try {
			//Cannot specify the encoding format, there will be garbled problems
			//FileReader reader = new FileReader(new File("w:/test.java"));
			
			System.out.println("The file viewed is: "+fir.getName());
			System.out.println("The path of the current file is "+fir.getPath());
			//You can specify the encoding format.
			InputStreamReader isr=new InputStreamReader(new FileInputStream(fir),"GBK");
			BufferedReader br = new BufferedReader(isr);
			String str = null;
			while ((str = br.readLine()) != null) {
				if(!str.startsWith("//")&&!str.equals("")){
					num++;
				}
			}
			System.out.println("The number of num is: "+num);
			br.close();
		} catch (Exception e) {
			e.printStackTrace ();
		}
		javaFileLinenum += num;
		System.out.println("The total amount of Java code is: "+javaFileLinenum);
	}
}

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326006685&siteId=291194637