Java comprehensive experiment

1, Topic introduction and analysis

Write a Java application to analyze a single java source program file and all Java source program files (including subdirectories) in a directory. The analysis contents include:

1) The number of Java source program files required for directory analysis.

2) The number of characters in the Java source program. When analyzing the directory, it is the sum of the number of characters in all source program files.

3) The number of comments in the Java source program file, that is, the total number of comments in the source program file, including single line comments and multi line comments. When analyzing a directory, it is the sum of all source program files in it.

4) The number of characters of comments in the Java source program file, that is, the sum of the number of characters of all comments in the source program file. When analyzing a directory, it is the sum of all source program files in it.

5) Keyword usage in Java source program files, that is, how many times each keyword in the source program file is used. When analyzing a directory, it is the sum of all source program files in it.


Specific requirements are as follows:

  1. When the program runs, the menu shown below is displayed first:
    ---------------- MENU -------------
    1. Analyze the directory or source program file
    2. View existing analysis results
    0. Exit
    ----------------------------------------
    Please select:

  1. When selecting menu item 1, you are first asked to enter the directory name or Java source file name to be analyzed.

    1) If the entered directory or file name does not exist, the prompt does not exist; When the extension of the entered file name is not ". Java", it will be prompted that it is not a java source program file.

    2) If you enter a Java source file name, analyze the source file.

    3) If you enter a directory name, analyze all source program files in the directory.

    4) The analysis results are stored in a text file, a data directory is established in the current directory, and the result file is placed in the data directory.

    Result file name when analyzing Directory: D_ Directory name_ Result.txt, for example: D_lang_Result.txt

    Result file name when analyzing source program file: F_ Source file name_ Result.txt, for example: F_String.java_Result.txt

    5) Format of content in result file:

    Line 1: analysis Directory: C:Program\Files\Java\jdk1.8.0_31\src\java

    Line 2: blank line

    Line 3: number of Java source program files: 1866 (no such line when analyzing the file)

    Line 4: total number of characters in the source program: 29022541

    Line 5: total number of notes: 57349

    Line 6: comment total characters: 17559371

    Line 7: blank line

    Line 8: keyword usage is as follows:

    Line 9: [int = 27705] (output each keyword and the number of times it is used from line 9, one per line)

    explain:

    At the end of the analysis, the analysis results are not displayed, and the results are stored in a text file. The following prompt is displayed:

    After directory analysis, the analysis results are stored in the file [data/D_util_Result.txt]!

    Or:

    After the file analysis, the analysis results are stored in the file [data/F_String.java_Result.txt]!

    When keyword is output, it is sorted from the largest to the smallest by the number of times used. When the number of times is the same, it is sorted alphabetically.

    All keywords of Java language

public static final String[] KEYWORDS = { "abstract", "assert", "boolean", "break", "byte", "case", 
"catch", "char", "class", "const", "continue", "default", "do", "double", "else", "enum", "extends",
 "final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", 
 "long", "native", "new", "package", "private", "protected", "public", "return", "short", "static", 
 "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "try", "void", 
 "volatile", "while" }; 



  1. View existing analysis result requirements

    When selecting menu item 2, first list the results that have been analyzed and stored, as follows:
    -----------------------------------
    1–D_test.java_Result.txt
    2–D_test2.java_Result.txt
    ------------------------------------
    Enter the file number to view:

    That is, all analysis result files stored in the data directory are listed and a sequence number is given.

    After entering the serial number of the file to view, the contents of the file are displayed. For example:
    ------------------------------------------------------------------------------------------------------
    Analysis Directory: D:\Java\Java experimental questions \ Comprehensive\test.java

    Number of Java source program files: 5
    Total number of characters in the source program: 9432
    Total number of notes: 59
    Total characters of comments: 2361

    The usage of keywords is as follows:
    [public = 32]
    [return = 14]
    [static = 14]
    [double = 12]
    [if = 10]
    [private = 10]
    [this = 10]
    [void = 10]
    [int = 8]
    [new = 8]
    [char = 5]
    [class = 5]
    [for = 5]
    [package = 5]
    [boolean = 4]
    [final = 4]
    [import = 4]
    [while = 2]
    [break = 1]
    [else = 1]
    ----------------------------------------------------------------------------------------------



2, Relevant tips
  1. When analyzing the number of comments and the number of characters of comments, it is assumed that there is no problem of comment nesting. That is, there are no following conditions in the files and directories used for the test:

    /**/ / Note 1*/

    //Note 2 / **/

  2. When analyzing the number of comments and characters of comments, it is assumed that there is no comment form in the string direct quantity, that is, there is no following situation:

    String s = "/abcd/";

  3. When analyzing keyword usage times, note that the number of keywords cannot be calculated in the following cases:

    (1) Keywords appearing in comments, such as the following int, cannot be counted

    /**

    * int k=0;

    */

    (2) Keywords in string literals, such as the following int, cannot be counted

     System.out.println("input a int: "); 
    

    (3) Pay attention to whole word recognition. For example, int in println is not a keyword and cannot be counted.

  4. If regular expressions are used for programming, in addition to basic regular expressions, you can refer to the following two classes in Java:

    java.util.regex.Pattern

    java.util.regex.Matcher

3, Source code
  1. directory structure

  1. Introduction of each class





  1. Operation results





  1. code

Functions class

package cn.zg.frame;

import cn.zg.module.Comment;
import cn.zg.module.Keyword;
import cn.zg.module.LookUpFile;
import cn.zg.module.SaveFile;
import cn.zg.utils.*;

import java.io.File;
import java.util.Objects;
import java.util.Scanner;



/**
 * @author zg
 */
public class Functions {

    public static final String JAVA_SUFFIX=".java";
    /**
     * Function 1: analyze directory or source program files
     */
    public static void evaluate() {
        String input=new Scanner(System.in).next();
        System.out.println();
        File file = new File(input);
        if(!file.exists()){
            //  The directory or file name does not exist
            System.out.print("The directory or file name you entered does not exist,Please reselect:");
            evaluate();
        }else if(!input.toLowerCase().endsWith(JAVA_SUFFIX)){
            //  Files that do not end in. java
            System.out.print("What you entered is not Java Source program file,Please re-enter:");
            evaluate();
        }else if(file.isDirectory()){
            //  catalogue
            dirEvaluate(input);
        }else{
            //  file
            fileEvaluate(input);
        }
    }

    /**
     * Analysis directory
     * @param dir Directory name
     */
    public static void dirEvaluate(String dir) {
        System.out.println("Analysis directory          :"+dir);
        System.out.println();
        System.out.println("Java Number of source program files :"+dir);
        System.out.println("Total number of characters in the source program :"+String.format("%10d",InTotalCharsUtil.dirCharsCount(dir)) );
        System.out.println("Total number of notes        :"+String.format("%10d",Comment.dirCommentCounts(dir)));
        System.out.println("Total number of characters in comments     :"+String.format("%10d",Comment.dirCommentChars(dir)));
        System.out.println();
        System.out.println("The usage of keywords is as follows:");
        //  Print keyword usage
        Keyword.print(dir);
        //  Save analysis results
        SaveFile.saveDir(dir);
    }

    /**
     * Java Source program analysis
     * @param file file name
     */
    public static void fileEvaluate(String file) {
        System.out.println("parse file           :"+file);
        System.out.println();
        System.out.println("Total number of characters in the source program  :"+String.format("%10d",InTotalCharsUtil.javaCharsCount(file)) );
        System.out.println("Total number of notes        :"+String.format("%10d",Comment.fileCommentCounts(file)));
        System.out.println("Total number of characters in comments     :"+String.format("%10d",Comment.fileCommentChars(file)));
        System.out.println();
        System.out.println("The usage of keywords is as follows:");
        //  Print keyword usage
        Keyword.print(file);
        //  Save analysis results
        SaveFile.saveFile(file);
    }


    /**
     * Function 2: view the analyzed results
     */
    public static void lookUp() {
        File file = new File("src\\data");
        if(file.isDirectory()){
            File[] files = file.listFiles();
            if (files != null&&files.length>0) {
                //  If there are analysis results
                System.out.println("-----------------------------------");
                for (File f : files) {
                    System.out.println(f.getName());
                }
                System.out.println("------------------------------------");
            }else{
                //  If there are no analysis results
                System.out.print("At present, there is no analysis of files or directories,Please select another function:");
                Start.function();
            }

            System.out.print("Enter the file number to view:");
            int input=new Scanner(System.in).nextInt();
            if(input<1||input> Objects.requireNonNull(files).length){
                System.out.print("The document number entered is incorrect,Please re-enter the document number:");
                input=new Scanner(System.in).nextInt();
                System.out.println();
                System.out.println();
                System.out.println();
            }
            System.out.println();
            System.out.println();
            if (files != null) {
                //  View specific analysis results
                LookUpFile.lookUp(files[input-1].getAbsolutePath());
            }

        }
    }

}



Initial interface Start class

package cn.zg.frame;

import java.util.Scanner;

import static cn.zg.frame.Functions.evaluate;
import static cn.zg.frame.Functions.lookUp;

/**
 * @author zg
 */
public class Start {

    /**
     * Selection of function 1: analysis directory or file
     */
    public static final int EVALUATE_DIR_OR_FILE=1;
    /**
     * Selection of function 2: view the analyzed results
     */
    public static final int LOOK_UP_RESULT=2;
    /**
     * Exit selection
     */
    public static final int EXIT=0;

    /**
     * menu
     */
    public static void mainFrame(){
        System.out.println("-----------MENU-----------");
        System.out.println("  1.Analysis directory or source program file    ");
        System.out.println("  2.View existing analysis results       ");
        System.out.println("  0.sign out                   ");
        System.out.println("--------------------------");
        System.out.print(" Please select:");
        function();
    }



    /**
     * Select the function in the menu
     */
    public static void function() {
        int input=new Scanner(System.in).nextInt();
        if(input==EVALUATE_DIR_OR_FILE){
            System.out.print("Please enter the name of the directory to analyze or Java Source file name:");
            //  Function 1: analyze directory or source program files
            evaluate();
        }else if(input==LOOK_UP_RESULT){
            System.out.println();
            System.out.println();
            // View analyzed results
            lookUp();
            System.out.println();
            System.out.println();
        }else if(input==EXIT){
            System.exit(0);
        }else{
            mainFrame();
        }
    }
}



Start class Main

package cn.zg.main;

import cn.zg.frame.Start;

/**
 * @author zg
 */
public class Main {
    public static void main(String[] args) {
        Start.mainFrame();
    }
}



Comment class:

package cn.zg.module;

import cn.zg.utils.CommentCountsAndCharsUtil;
import cn.zg.utils.TextIntoListUtil;

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

/**
 * @author zg
 */
public class Comment {

    /**
     *
     * @param filePath Path to file
     * @return Number of comments in the file
     */
    public static long fileCommentCounts(String filePath){
        //  Save the file into the array
        ArrayList<String> list = TextIntoListUtil.fileList(filePath);
        long[] countsAndChars = CommentCountsAndCharsUtil.operateNote(list);
        return countsAndChars[0];
    }

    /**
     *
     * @param filePath Path to file
     * @return The number of characters in the comment of the file
     */
    public static long fileCommentChars(String filePath){
        ArrayList<String> list = TextIntoListUtil.fileList(filePath);
        long[] countsAndChars = CommentCountsAndCharsUtil.operateNote(list);
        return countsAndChars[1];
    }

    /**
     *
     * @param dirPath Path to directory
     * @return  Number of comments for all java files in the directory
     */
    public static long dirCommentCounts(String dirPath){
        long count=0;
        File dir = new File(dirPath);
        File[] files = dir.listFiles();
        if(files==null){
            return 0;
        }
        for (File f : files) {
            if(f.isFile()){
                count+=fileCommentCounts(f.getAbsolutePath());
            }else{
                count+=dirCommentCounts(f.getAbsolutePath());
            }
        }
        return count;
    }

    /**
     *
     * @param dirPath Path to directory
     * @return Number of comments for all java files in the directory
     */
    public static long dirCommentChars(String dirPath){
        long count=0;
        File dir = new File(dirPath);
        File[] files = dir.listFiles();
        if(files==null){
            return 0;
        }
        for (File f : files) {
            if(f.isFile()){
                count+=fileCommentChars(f.getAbsolutePath());
            }else{
                count+=dirCommentChars(f.getAbsolutePath());
            }
        }
        return count;
    }
}



FileID class

package cn.zg.module;

import java.io.Serializable;

/**
 * @author zg
 */
public class FileID implements Serializable {

    /**
     * No matter how the class is changed, a new serialization ID will not be generated
     */
    private static final long serialVersionUID=1L;

    private int id;

    public FileID() {
    }

    public FileID(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}



Keyword class

package cn.zg.module;

import cn.zg.utils.KeySelectUtil;

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


/**
 * @author zg
 */
public class Keyword {

    /**
     *
     * @param fileName File path
     * @return Save the results of keyword usage into the file
     */
    public static ArrayList<String> writeIntoFile(String fileName){
        File file = new File(fileName);
        ArrayList<String> returnList = new ArrayList<>();
        Map<String, Integer> map;
        if(file.isFile()){
            map = KeySelectUtil.fileCountKeyWords(fileName);
        }else{
            map = KeySelectUtil.dirCountKeyWords(fileName);
        }
        List<Map.Entry<String, Integer>> list = null;
        if (map != null) {
            list = KeySelectUtil.mapIntoListAndSort(map);
        }
        if (list != null) {
            for (Map.Entry<String, Integer> stringIntegerEntry : list) {
                if(stringIntegerEntry.getValue()>0){
                    returnList.add("["+String.format("%-15s",stringIntegerEntry.getKey())+
                            "="+String.format("%5d",stringIntegerEntry.getValue())+"]");
                }
            }
        }
        return returnList;
    }

    /**
     *
     * @param fileName File path
     * Print the results of keyword usage
     */
    public static void print(String fileName){
        File file = new File(fileName);
        Map<String, Integer> map;
        if(file.isFile()){
            map = KeySelectUtil.fileCountKeyWords(fileName);
        }else{
            map = KeySelectUtil.dirCountKeyWords(fileName);
        }
        List<Map.Entry<String, Integer>> list = null;
        if (map != null) {
            list = KeySelectUtil.mapIntoListAndSort(map);
        }
        if (list != null) {
            for (Map.Entry<String, Integer> stringIntegerEntry : list) {
                if(stringIntegerEntry.getValue()>0){
                    System.out.println("["+String.format("%-15s",stringIntegerEntry.getKey())+
                            "="+String.format("%5d",stringIntegerEntry.getValue())+"]");
                }
            }
        }
    }
}



LookUpFile class

package cn.zg.module;

import cn.zg.frame.Functions;
import cn.zg.frame.Start;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

/**
 * @author zg
 */
public class LookUpFile {
    /**
     *
     * @param absolutePath The path where the keyword file is stored
     *  Read data file
     */
    public static void lookUp(String absolutePath) {
        try(BufferedReader bufferedReader = new BufferedReader(new FileReader(absolutePath))){
            String str;
            while((str=bufferedReader.readLine())!=null){
                System.out.println(str);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        System.out.println();
        System.out.println();
        System.out.print("To return to the main menu, enter 1,To return to the previous level, enter 2,To exit, enter 0:");
        boolean loop=true;

        while(loop){
            int input=new Scanner(System.in).nextInt();
            if(input==1){
                System.out.println();
                System.out.println();
                Start.mainFrame();
                loop=false;
            }else if(input==0){
                loop=false;
                System.exit(0);
            }else if(input==2){
                System.out.println();
                System.out.println();
                Functions.lookUp();
            }else{
                System.out.print("Wrong input! Please re-enter! To return to the main menu, enter 1,To return to the previous level, enter 2,To exit, enter 0:");
            }
        }
    }
}



SaveFile class

package cn.zg.module;

import cn.zg.utils.InTotalCharsUtil;
import cn.zg.utils.JavaFileCountUtil;
import cn.zg.utils.OtherUtils;

import java.io.*;
import java.util.ArrayList;

/**
 * @author zg
 */
public class SaveFile {


    /**
     * Read id from serialization file of id
     * @return id
     */
    public static int getId(){
        int id = 0;
        try(ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("src\\id\\id.txt"))){
            FileID obj = (FileID)objectInputStream.readObject();
            id= obj.getId();
        }catch (IOException | ClassNotFoundException e){
            e.printStackTrace();
        }
        return id;
    }

    /**
     * Update id
     * @param id  Original id
     */
    public static void setId(int id){
        try(ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("src\\id\\id.txt"))){
            objectOutputStream.writeObject(new FileID(id));
        }catch (IOException e){
            e.printStackTrace();
        }
    }


    /**
     * Store the analysis results of the directory
     * @param dirPath Directory name
     */
    public static void saveDir(String dirPath){
        int id=getId();
        id++;
        setId(id);
        File file = new File(dirPath);
        String path=""+id+"--D_"+file.getName()+"_Result.txt";
        try(final BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("src\\data\\"+path))){
            String[] strings={
                    "------------------------------------------------",
                    "Analysis directory          :"+dirPath,
                    "Java Number of source program files :"+ JavaFileCountUtil.javaFileCount(dirPath),
                    "Total number of characters in the source program :"+ InTotalCharsUtil.dirCharsCount(dirPath),
                    "Total number of notes        :"+Comment.dirCommentCounts(dirPath),
                    "Total number of characters in comments     :"+ Comment.dirCommentChars(dirPath),
                    "The usage of keywords is as follows:"
            };
            for(int i=0;i<strings.length;i++){
                bufferedWriter.write(strings[i]);
                bufferedWriter.newLine();
                if(i==1||i==5){
                    bufferedWriter.newLine();
                }
            }
            ArrayList<String> list = Keyword.writeIntoFile(dirPath);
            for (String s : list) {
                bufferedWriter.write(s);
                bufferedWriter.newLine();
            }
            bufferedWriter.write("------------------------------------------------");
        }catch (IOException e){
            e.printStackTrace();
        }
        OtherUtils.returnOrNotFile(path);
    }

    /**
     * Store the analysis results of the file
     * @param filePath Path to file
     */
    public static void saveFile(String filePath){
        int id=getId();
        id++;
        setId(id);
        File file = new File(filePath);
        String path=""+id+"--F_"+file.getName()+"_Result.txt";
        try(final BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("src\\data\\"+path))){
            String[] strings={
                    "------------------------------------------------",
                    "parse file          :"+filePath,
                    "Total number of characters in the source program :"+ InTotalCharsUtil.javaCharsCount(filePath),
                    "Total number of notes        :"+Comment.fileCommentCounts(filePath),
                    "Total number of characters in comments     :"+ Comment.fileCommentChars(filePath),
                    "The usage of keywords is as follows:"
            };
            for(int i=0;i<strings.length;i++){
                bufferedWriter.write(strings[i]);
                bufferedWriter.newLine();
                if(i==1||i==4){
                    bufferedWriter.newLine();
                }
            }
            ArrayList<String> list = Keyword.writeIntoFile(filePath);
            for (String s : list) {
                bufferedWriter.write(s);
                bufferedWriter.newLine();
            }
            bufferedWriter.write("------------------------------------------------");
        }catch (IOException e){
            e.printStackTrace();
        }
        OtherUtils.returnOrNotDir(path);
    }
}


CommentCountsAndCharsUtil class

package cn.zg.utils;

import java.util.ArrayList;

/**
 *
 * Tool class for the number of comments and characters
 *
 * @author zg
 */
public class CommentCountsAndCharsUtil {

    /**
     * End of multiline comment
     */
    public static final String END_OF_COMMENT="*/";
    /**
     * Single-Line Comments 
     */
    public static final String SINGLE_LINE_COMMENT="//";


    /**
     *
     * @param list Array of storage files
     * @return An array of only the number of comments and the number of characters
     */
    public static long[] operateNote(ArrayList<String> list){
        String str;
        long countNote=0;
        long charInNote = 0;
        for(int i=0;i<list.size();i++) {

            str=list.get(i);
            int note1=str.indexOf("/*");
            int note2=str.indexOf("//");
            int note3=str.indexOf("*/");

            //  Double quotation mark
            String dm="\"(.*)\"";


            if(note1!=-1&&note3==-1) {
                //  multiline comment 
                countNote++;
                String ttt=list.get(i);
                list.set(i, ttt.substring(0, note1));
                //  +1 is including line breaks
                charInNote+=str.substring(note1).length()+1;

                str=list.get(++i);
                while(!str.contains(END_OF_COMMENT)) {
                    if(str.contains(SINGLE_LINE_COMMENT)) {
                        countNote++;
                    }
                    list.set(i,"");

                    charInNote+=str.length()+1;
                    if(i<list.size()-1) {
                        str=list.get(++i);
                    }else {
                        break;
                    }
                }
                list.set(i,"");
                charInNote+=str.length();

            }else if(note2!=-1) {
                //  Single line comment for "/ /" class
                countNote++;
                list.set(i, str.substring(0,note2));
                charInNote+=str.substring(note2).length()+1;
            }else if(note1 != -1) {
                //  Single-Line Comments 
                countNote++;

                String m1=str.substring(0, note1);
                String m2=str.substring(note3+2);
                String m3=m1+m2;
                charInNote+=str.substring(note1, note3+2).length();
                list.set(i, m3);
            }else {
                //  Delete output statement
                String rp=list.get(i);
                rp=rp.replaceAll(dm, "");
                list.set(i, rp);
            }

        }
        return new long[]{countNote,charInNote};
    }

}



InTotalCharsUtil

package cn.zg.utils;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/**
 * @author zg
 * Count the total number of characters
 */
public class InTotalCharsUtil {

    public static final String JAVA_SUFFIX=".java";
    /**
     *
     * @param str Java file name
     * @return java Number of characters in the file
     */
    public static long javaCharsCount(String str) {
        long count=0;
        try(FileReader fileReader = new FileReader(new File(str))){
            while(fileReader.read()!=-1){
                count++;
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        return count;
    }

    /**
     *
     * @param dir Directory name
     * @return The total number of characters of all source programs in the directory
     */
    public static long dirCharsCount(String dir) {
        long count=0;
        File file = new File(dir);
        File[] files = file.listFiles((dir1,name)->
                new File(dir1,name).isDirectory()||name.toLowerCase().endsWith(JAVA_SUFFIX));
        if(files==null){
            return 0;
        }
        for (File f : files) {
            if(f.isFile()){
                //  getAbsolutePath() uses an absolute path
                count+= javaCharsCount(f.getAbsolutePath());
            }else{
                count+= dirCharsCount(f.getAbsolutePath());
            }
        }
        return count;
    }
}



JavaFileCountUtil

package cn.zg.utils;

import java.io.File;

/**
 * @author zg
 */
public class JavaFileCountUtil {

    public static final String JAVA_SUFFIX=".java";

    /**
     *
     * @param str Directory name
     * @return Java Number of source program files
     */
    public static int javaFileCount(String str) {
        int count=0;
        File dir = new File(str);
        //  Filter to get folders and files ending in. java
        File[] files = dir.listFiles((dir1,name)->
                new File(dir1,name).isDirectory()||name.toLowerCase().endsWith(JAVA_SUFFIX));
        if(files==null) {
            // If the file array is empty, the passive program file
            return 0;
        }
        for (File f : files) {
            if (f.isFile()){
                count++;
            }else{
                //  getAbsolutePath() uses an absolute path
                count+=javaFileCount(f.getAbsolutePath());
            }
        }
        return count;
    }
}



KeySelectUtil

package cn.zg.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;

/**
 * @author zg
 */
public class KeySelectUtil {

    public static final String[] KEYWORDS = {
            "abstract", "assert", "boolean", "break", "byte", "case", "catch",
            "char", "class", "const", "continue", "default", "do", "double", "else",
            "enum", "extends", "final", "finally", "float", "for", "goto", "if",
            "implements", "import", "instanceof", "int", "interface", "long", "native",
            "new", "package", "private", "protected", "public", "return", "short",
            "static", "strictfp", "super", "switch", "synchronized", "this", "throw",
            "throws", "transient", "try", "void", "volatile", "while"
    };

    public static final String END_OF_DOC="*/";
    public static final String JAVA_SUFFIX=".java";

    /**
     * Read a line in the file, split the line into a string array, and judge whether it is a keyword one by one. First, remove the influence of non alphanumeric characters
     * @param line file name
     * @param keywords Hash array
     */
    public static void matchKeywords(String line, Map<String,Integer> keywords) {
        //  Use the regular expression "\ \ W" to match any non word characters, replace them with spaces, and then split the text with spaces
        String[] wordList = line.replaceAll("\\W", " ").split(" ");
        for (String s : wordList) {
            //  Traversal character set
            for (String keyword : KEYWORDS) {
                //Circular judgment
                if (keyword.equals(s)) {
                    //  If the character matches the keyword in the keyword list, the value corresponding to the key + 1
                    keywords.put(keyword, keywords.get(keyword)+1);
                }
            }
        }
    }


    /**
     *
     * @param fileName  java File pathname
     * @return list collection with keyword and keyword number map
     */
    public  static Map<String, Integer> fileCountKeyWords(String fileName) {
        Map<String, Integer> keywords = new HashMap<>(50);
        try (BufferedReader input = new BufferedReader(new FileReader(fileName))) {
            for (String word : KEYWORDS) {
                //Initialize Map in keyword order
                keywords.put(word,0);
            }

            String line;
            while ((line = input.readLine()) != null) {
                //  Remove the spaces at the beginning and end of the string
                line = line.trim();
                if (line.startsWith("//")) {
                    //  Single-Line Comments 
                    continue;
                } else if (line.contains("/*")) {
                    //  Multiline, document and trailing comments
                    if (!line.startsWith("/*")) {
                        //The first line is the code, and the rest is the comment
                        matchKeywords(line, keywords);
                    }
                    while (!line.endsWith(END_OF_DOC)) {
                        //  If not“*/"ending

                        //  Remove the spaces at the beginning and end of the string
                        //  line = input.readLine().trim()
                        String readLine = input.readLine();
                        if(readLine!=null){
                            line= readLine.trim();
                        }
                    }
                }
                //Statistics on code lines
                matchKeywords(line,keywords);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        return keywords;
    }


    /**
     *
     * @param fileName  Directory pathname
     * @return list collection with keyword and keyword number map
     */
    public  static Map<String, Integer> dirCountKeyWords(String fileName){
        File file = new File(fileName);
        File[] files = file.listFiles((dir1,name)->
                new File(dir1,name).isDirectory()||name.toLowerCase().endsWith(JAVA_SUFFIX));

        Map<String, Integer> keywords = new HashMap<>(50);
        for (String word : KEYWORDS) {
            //Initialize Map in keyword order
            keywords.put(word,0);
        }

        if(files==null){
            return null;
        }
        for (File f : files) {
            if(f.isFile()){
                //           getAbsolutePath() uses an absolute path
                Map<String, Integer> map = fileCountKeyWords(f.getAbsoluteFile().toString());
                for (String keyword : map.keySet()) {
                    keywords.put(keyword,keywords.get(keyword)+map.get(keyword));
                }
            }else{
                Map<String, Integer> map = dirCountKeyWords(f.getAbsoluteFile().toString());
                if (map != null) {
                    for (String keyword : map.keySet()) {
                        keywords.put(keyword,keywords.get(keyword)+map.get(keyword));
                    }
                }
            }
        }
        return keywords;
    }


    /**
     *
     * @param keywords map
     * @return map Convert to List array and sort
     */
    public static List<Map.Entry<String,Integer>> mapIntoListAndSort(Map<String, Integer> keywords){
        //  Convert map.entrySet() to list
        List<Map.Entry<String,Integer>> list= new ArrayList<>(keywords.entrySet());
        //  The descending order of values is preferred, and the dictionary order of keys with the same value is sorted
        list.sort((o1, o2) -> {
            if (o2.getValue().equals(o1.getValue())) {
                return String.CASE_INSENSITIVE_ORDER.compare(o1.getKey(), o2.getKey());
            }
            return o2.getValue() - o1.getValue();
        });
        return list;
    }
}



OtherUtils

package cn.zg.utils;

import cn.zg.frame.Start;

import java.util.Scanner;

/**
 * @author zg
 */
public class OtherUtils {

    public static void returnOrNotFile(String path){
        System.out.println("End of file analysis, The analysis results are stored in the file[data\\"+path+"]! ");
        System.out.println();
        System.out.println();
        System.out.print("To return to the previous level, enter 1,To exit, enter 0:");
        boolean loop=true;

        while(loop){
            int input=new Scanner(System.in).nextInt();
            if(input==1){
                Start.mainFrame();
                loop=false;
            }else if(input==0){
                loop=false;
                System.exit(0);
            }else{
                System.out.print("Error in input! Please re-enter! To return to the previous level, please enter 1,To exit, enter 0:");
            }
        }
    }

    /**
     * Return or exit
     * @param path File name of the data store
     */
    public static void returnOrNotDir(String path){
        System.out.println("End of catalog analysis, The analysis results are stored in the file[data\\"+path+"]! ");
        System.out.println();
        System.out.println();
        System.out.print("To return to the previous level, enter 1,To exit, enter 0:");
        boolean loop=true;

        while(loop){
            int input=new Scanner(System.in).nextInt();
            if(input==1){
                System.out.println();
                System.out.println();
                Start.mainFrame();
                loop=false;
            }else if(input==0){
                loop=false;
                System.exit(0);
            }else{
                System.out.print("Error in input! Please re-enter! To return to the previous level, please enter 1,To exit, enter 0:");
            }
        }
    }
}



TextIntoListUtil

package cn.zg.utils;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

/**
 * @author zg
 */
public class TextIntoListUtil {

    /**
     *
     * @param filePath File path
     * @return Save the file into the List array
     */
    public static ArrayList<String> fileList(String filePath){

        ArrayList<String> list = new ArrayList<>();
        try(final BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath))){
            String str;
            while((str=bufferedReader.readLine())!=null){
                list.add(str);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        return list;
    }
}

emm, but the format requirements are a little annoying.



Source code:

https://gitee.com/keepOrdinary/Comprehensive

Keywords: Java

Added by awared on Tue, 28 Sep 2021 22:21:07 +0300