Skip to content

Java 工具方法 #97

@mysterin

Description

@mysterin

这里记录 Java 的一些使用工具

import java.io.*;
import java.lang.reflect.*;

public class Utils {
    
    public static void main(String[] args) throws Exception {
        Utils utils = new Utils();
        Class clazz = Class.forName("Utils");
        Method method = clazz.getMethod(args[0]);
        method.invoke(utils);
    }

    public void help() {
        StringBuilder sb = new StringBuilder();
        sb.append("帮助说明文档\n");
        sb.append("============\n");
        sb.append("方法: kcl, 统计指定目录的文件有关键字的行数. 参数: -Dpath, -Dkey\n");
        sb.append("方法: kc, 统计指定目录的文件关键字个数. 参数: -Dpath, -Dkey\n");
        print(sb.toString());
    }

    /**
     * 统计文件有关键字的行数
     */
    public void kcl() throws IOException {
        kc(true);
    }

    /**
     * 统计文件关键字个数
     */
    public void kc() throws IOException {
        kc(false);
    }

    public void kc(boolean lineCounts) throws IOException {
        String path = System.getProperty("path");
        String key = System.getProperty("key");
        File file = new File(path);
        File[] files;
        if (file.isDirectory()) {
            files = file.listFiles();
        } else {
            files = new File[]{file};
        }
        int count = 0;
        for (File f : files) {
            if (f.isDirectory()) {
                continue;
            }
            print(f.getAbsolutePath());
            FileInputStream input = new FileInputStream(f);
            BufferedReader reader = new BufferedReader(new InputStreamReader(input));
            String line;
            while ((line = reader.readLine()) != null) {
                if (lineCounts) {
                    if (find(line, key) > 0) {
                        count++;
                    }
                } else {
                    count += find(line, key);
                }
            }
            reader.close();
        }
        print("count: " + count);
    }

    /**
     * 查找字符串包含关键字的个数
     */
    public int find(String s, String key) {
        int index = -1;
        int count = 0;
        while ((index = s.indexOf(key, index)) > -1) {
            count++;
            index += key.length();
        }
        return count;
    }

    public static void print(String msg) {
        System.out.println(msg);
    }
}

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions