java中StringUtils,FileUtils,PropertiesUtils,DataBaseUtils工具类简介说明

欣喜 Java经验 发布时间:2025-01-24 10:33:30 阅读数:16456 1
下文笔者讲述java中各工具类的简介说明,如下所示
- **StringUtils**:用于字符串操作,简化字符串处理。
- **FileUtils**:用于文件操作,简化文件读取、写入、复制等。
- **PropertiesUtils**:用于属性文件操作,简化属性文件的加载、读取、写入。
- **DataBaseUtils**:用于数据库操作,简化数据库连接、查询、更新等

字符串工具类
StringUtils

    package com.java265.generate.utils;
     
    import java.util.*;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
     
    public class StringUtils {
     
        public static String removeCrlf(String str) {
            if(str == null) return null;
            return StringUtils.join(StringUtils.tokenizeToStringArray(str,"\t\n\r\f")," ");
        }
     
        private static final Map<String,String> XML = new HashMap<String,String>();
     
        static{
            XML.put("apos", "'");
            XML.put("quot", "\"");
            XML.put("amp", "&");
            XML.put("lt", "<");
            XML.put("gt", ">");
        }
     
        public static String unescapeXml(String str) {
            if(str == null) return null;
            for(String key : XML.keySet()) {
                String value = XML.get(key);
                str = StringUtils.replace(str, "&"+key+";", value);
            }
            return str;
        }
     
     
        public static String removePrefix(String str,String prefix) {
            return removePrefix(str,prefix,false);
        }
     
       //去除前缀temp = StringUtils.removePrefix(temp,"tb_",true);   把数据库表名bs_user 转换成java类名
        public static String removePrefix(String str,String prefix,boolean ignoreCase) {
            if(str == null) return null;
            if(prefix == null) return str;
            if(ignoreCase) {
                if(str.toLowerCase().startsWith(prefix.toLowerCase())) {
                    return str.substring(prefix.length());
                }
            }else {
                if(str.startsWith(prefix)) {
                    return str.substring(prefix.length());
                }
            }
            return str;
        }
     
        public static boolean isBlank(String str) {
            return str == null || str.trim().length() == 0;
        }
     
        public static boolean isNotBlank(String str) {
            return !isBlank(str);
        }
     
        public static String getExtension(String str) {
            if(str == null) return null;
            int i = str.lastIndexOf('.');
            if(i >= 0) {
                return str.substring(i+1);
            }
            return null;
        }
     
        /**
         * Count the occurrences of the substring in string s.
         * @param str string to search in. Return 0 if this is null.
         * @param sub string to search for. Return 0 if this is null.
         */
        public static int countOccurrencesOf(String str, String sub) {
            if (str == null || sub == null || str.length() == 0 || sub.length() == 0) {
                return 0;
            }
            int count = 0;
            int pos = 0;
            int idx;
            while ((idx = str.indexOf(sub, pos)) != -1) {
                ++count;
                pos = idx + sub.length();
            }
            return count;
        }
         //判断是否包含 if(StringUtils.contains(columnName ,keys.split(","))) 
        public static boolean contains(String str,String... keywords) {
            if(str == null) return false;
            if(keywords == null) throw new IllegalArgumentException("'keywords' must be not null");
     
            for(String keyword : keywords) {
                if(str.equals(keyword)) {
                    return true;
                }
            }
            return false;
        }
     
        public static String defaultString(Object value) {
            if(value == null) {
                return "";
            }
            return value.toString();
        }
     
        public static String defaultIfEmpty(Object value,String defaultValue) {
            if(value == null || "".equals(value)) {
                return defaultValue;
            }
            return value.toString();
        }
     
        //首字母大写
        public static String makeAllWordFirstLetterUpperCase(String sqlName) {
            String[] strs = sqlName.toLowerCase().split("_");
            String result = "";
            String preStr = "";
            for(int i = 0; i < strs.length; i++) {
                if(preStr.length() == 1) {
                    result += strs[i];
                }else {
                    result += capitalize(strs[i]);
                }
                preStr = strs[i];
            }
            return result;
        }
     
        public static int indexOfByRegex(String input,String regex) {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(input);
            if(m.find()) {
                return m.start();
            }
            return -1;
        }
       // 把数据库列名create_time转换成java类属性名 -> createTime
        public static String toJavaVariableName(String str) {
            return uncapitalize(toJavaClassName(str));
        }
     
        public static String toJavaClassName(String str) {
            return makeAllWordFirstLetterUpperCase(StringUtils.toUnderscoreName(str));
        }
     
        public static String removeMany(String inString, String... keywords) {
            if (inString == null) {
                return null;
            }
            for(String k : keywords) {
                inString = replace(inString, k, "");
            }
            return inString;
        }
     
        public static String replace(String inString, String oldPattern, String newPattern) {
            if (inString == null) {
                return null;
            }
            if (oldPattern == null || newPattern == null) {
                return inString;
            }
     
            StringBuffer sbuf = new StringBuffer();
            // output StringBuffer we'll build up
            int pos = 0; // our position in the old string
            int index = inString.indexOf(oldPattern);
            // the index of an occurrence we've found, or -1
            int patLen = oldPattern.length();
            while (index >= 0) {
                sbuf.append(inString.substring(pos, index));
                sbuf.append(newPattern);
                pos = index + patLen;
                index = inString.indexOf(oldPattern, pos);
            }
            sbuf.append(inString.substring(pos));
     
            // remember to append any characters to the right of a match
            return sbuf.toString();
        }
        /**����ĸ��copy from spring*/
        public static String capitalize(String str) {
            return changeFirstCharacterCase(str, true);
        }
     
        /**����ĸСдcopy from spring*/
        public static String uncapitalize(String str) {
            return changeFirstCharacterCase(str, false);
        }
        /**copy from spring*/
        private static String changeFirstCharacterCase(String str, boolean capitalize) {
            if (str == null || str.length() == 0) {
                return str;
            }
            StringBuffer buf = new StringBuffer(str.length());
            if (capitalize) {
                buf.append(Character.toUpperCase(str.charAt(0)));
            }
            else {
                buf.append(Character.toLowerCase(str.charAt(0)));
            }
            buf.append(str.substring(1));
            return buf.toString();
        }
     
        private static final Random RANDOM = new Random();
        public static String randomNumeric(int count) {
            return random(count, false, true);
        }
     
        public static String random(int count, boolean letters, boolean numbers) {
            return random(count, 0, 0, letters, numbers);
        }
     
        public static String random(int count, int start, int end, boolean letters, boolean numbers) {
            return random(count, start, end, letters, numbers, null, RANDOM);
        }
     
        public static String random(int count, int start, int end, boolean letters,
                                    boolean numbers, char[] chars, Random random) {
            if (count == 0) {
                return "";
            } else if (count < 0) {
                throw new IllegalArgumentException(
                        "Requested random string length " + count
                                + " is less than 0.");
            }
            if ((start == 0) && (end == 0)) {
                end = 'z' + 1;
                start = ' ';
                if (!letters && !numbers) {
                    start = 0;
                    end = Integer.MAX_VALUE;
                }
            }
     
            char[] buffer = new char[count];
            int gap = end - start;
     
            while (count-- != 0) {
                char ch;
                if (chars == null) {
                    ch = (char) (random.nextInt(gap) + start);
                } else {
                    ch = chars[random.nextInt(gap) + start];
                }
                if ((letters && Character.isLetter(ch))
                        || (numbers && Character.isDigit(ch))
                        || (!letters && !numbers)) {
                    if (ch >= 56320 && ch <= 57343) {
                        if (count == 0) {
                            count++;
                        } else {
                            // low surrogate, insert high surrogate after putting it
                            // in
                            buffer[count] = ch;
                            count--;
                            buffer[count] = (char) (55296 + random.nextInt(128));
                        }
                    } else if (ch >= 55296 && ch <= 56191) {
                        if (count == 0) {
                            count++;
                        } else {
                            // high surrogate, insert low surrogate before putting
                            // it in
                            buffer[count] = (char) (56320 + random.nextInt(128));
                            count--;
                            buffer[count] = ch;
                        }
                    } else if (ch >= 56192 && ch <= 56319) {
                        // private high surrogate, no effing clue, so skip it
                        count++;
                    } else {
                        buffer[count] = ch;
                    }
                } else {
                    count++;
                }
            }
            return new String(buffer);
        }
     
        /**
         */
        public static String toUnderscoreName(String name) {
            if(name == null) return null;
     
            String filteredName = name;
            if(filteredName.indexOf("_") >= 0 && filteredName.equals(filteredName.toUpperCase())) {
                filteredName = filteredName.toLowerCase();
            }
            if(filteredName.indexOf("_") == -1 && filteredName.equals(filteredName.toUpperCase())) {
                filteredName = filteredName.toLowerCase();
            }
     
            StringBuffer result = new StringBuffer();
            if (filteredName != null && filteredName.length() > 0) {
                result.append(filteredName.substring(0, 1).toLowerCase());
                for (int i = 1; i < filteredName.length(); i++) {
                    String preChart = filteredName.substring(i - 1, i);
                    String c = filteredName.substring(i, i + 1);
                    if(c.equals("_")) {
                        result.append("_");
                        continue;
                    }
                    if(preChart.equals("_")){
                        result.append(c.toLowerCase());
                        continue;
                    }
                    if(c.matches("\\d")) {
                        result.append(c);
                    }else if (c.equals(c.toUpperCase())) {
                        result.append("_");
                        result.append(c.toLowerCase());
                    }
                    else {
                        result.append(c);
                    }
                }
            }
            return result.toString();
        }
     
        public static String removeEndWiths(String inputString,String... endWiths) {
            for(String endWith : endWiths) {
                if(inputString.endsWith(endWith)) {
                    return inputString.substring(0,inputString.length() - endWith.length());
                }
            }
            return inputString;
        }
     
        /**
         * 将string转换为list<ColumnEnum> 格式为: "enumAlias(enumKey,enumDesc)"
         */
        static Pattern three = Pattern.compile("(.*)\\((.*),(.*)\\)");
        static Pattern two = Pattern.compile("(.*)\\((.*)\\)");
     
        /**
         * Test whether the given string matches the given substring
         * at the given index.
         * @param str the original string (or StringBuilder)
         * @param index the index in the original string to start matching against
         * @param substring the substring to match at the given index
         */
        public static boolean substringMatch(CharSequence str, int index, CharSequence substring) {
            for (int j = 0; j < substring.length(); j++) {
                int i = index + j;
                if (i >= str.length() || str.charAt(i) != substring.charAt(j)) {
                    return false;
                }
            }
            return true;
        }
     
        public static String[] tokenizeToStringArray(String str,String seperators) {
            if(str == null) return new String[0];
            StringTokenizer tokenlizer = new StringTokenizer(str,seperators);
            List result = new ArrayList();
     
            while(tokenlizer.hasMoreElements()) {
                Object s = tokenlizer.nextElement();
                result.add(s);
            }
            return (String[])result.toArray(new String[result.size()]);
        }
        public static String join(List list, String seperator) {
            return join(list.toArray(new Object[0]),seperator);
        }
     
        public static String replace(int start, int end, String str,String replacement) {
            String before = str.substring(0,start);
            String after = str.substring(end);
            return before + replacement + after;
        }
     
        public static String join(Object[] array, String seperator) {
            if(array == null) return null;
            StringBuffer result = new StringBuffer();
            for(int i = 0; i < array.length; i++) {
                result.append(array[i]);
                if(i != array.length - 1)  {
                    result.append(seperator);
                }
            }
            return result.toString();
        }
     
        public static int containsCount(String string, String keyword) {
            if(string == null) return 0;
            int count = 0;
            for(int i = 0; i < string.length(); i++ ) {
                int indexOf = string.indexOf(keyword,i);
                if(indexOf < 0) {
                    break;
                }
                count ++;
                i = indexOf;
            }
            return count;
        }
    }

2.文件工具类
FileUtils

    package com.java265.generate.utils;
     
    import java.io.*;
    import java.net.URL;
    import java.util.*;
     
    //文件处理工具类
    public class FileUtils {
     
        // 得到相对路径
        public static String getRelativePath(File baseDir,File file) {
            if(baseDir.equals(file))
                return "";
            if(baseDir.getParentFile() == null)
                return file.getAbsolutePath().substring(baseDir.getAbsolutePath().length());
            return file.getAbsolutePath().substring(baseDir.getAbsolutePath().length()+1);
        }
     
        //查询某个目录下的所有文件
        public static List<File> searchAllFile(File dir) throws IOException {
            ArrayList arrayList = new ArrayList();
            searchFiles(dir,arrayList);
            return arrayList;
        }
     
        //递归获取某个目录下的所有文件
        public static void searchFiles(File dir,List<File> collector) throws IOException {
            if(dir.isDirectory()) {
                File[] subFiles = dir.listFiles();
                for(int i = 0; i < subFiles.length; i++) {
                    searchFiles(subFiles[i],collector);
                }
            }else{
                collector.add(dir);
            }
        }
     
        //创建文件
        public static File mkdir(String dir,String file) {
            if(dir == null) throw new IllegalArgumentException("dir must be not null");
            File result = new File(dir,file);
            if(result.getParentFile() != null) {
                result.getParentFile().mkdirs();
            }
            return result;
        }
    }

3.PropertiesUtils

    package com.java265.generate.utils;
     
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.util.*;
     
    /**
     * 需要将自定义的配置信息写入到properties文件中
     *      配置到相对于工程的properties文件夹下
     */
    public class PropertiesUtils {
     
        //自定义的数据模型map集合
        public static Map<String,String> customMap = new HashMap<>();
     
        static {
            File dir = new File("properties");
            try {
                //查询某个目录下的所有文件
                List<File> files = FileUtils.searchAllFile(new File(dir.getAbsolutePath()));
                for (File file : files) {
                    if(file.getName().endsWith(".properties")) {
                        Properties prop = new Properties();
                        prop.load(new FileInputStream(file));
                        customMap.putAll((Map) prop);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
     
        public static void main(String[] args) {
            PropertiesUtils.customMap.forEach((k, v)->{
                System.out.println(k+"--"+v);
            });
        }
    }

jdbc工具类
DataBaseUtils

    package com.java265.generate.utils;
     
    import com.java265.generate.entity.Column;
    import com.java265.generate.entity.DataBase;
    import com.java265.generate.entity.Table;
     
    import java.sql.*;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Properties;
     
    public class DataBaseUtils {
     
        //获取到mysql中所有的数据库名称
     
        //获取数据库连接
        public static Connection getConnection(DataBase db) throws Exception {
            Properties props = new Properties();
            props.put("remarksReporting","true");//获取数据库的备注信息
            props.put("user",db.getUserName());
            props.put("password",db.getPassWord());
            Class.forName(db.getDriver());//注册驱动
            return DriverManager.getConnection(db.getUrl(),props);
        }
     
     
        //获取数据库列表
        public static List<String> getSchemas(DataBase db) throws Exception {
            //1.获取元数据
            Connection connection = getConnection(db);
            DatabaseMetaData metaData = connection.getMetaData();
            //2.获取所有数据库列表
            ResultSet rs = metaData.getCatalogs();
            List<String> list = new ArrayList<>();
            while (rs.next()) {
                list.add(rs.getString(1));
            }
            rs.close();
            connection.close();
            return list;
        }
     
        /**
         * 获取数据库中的表和字段构造实体类
         *      Table对象
         *
         *  1.参数
         *      DataBase 数据库对象
         *  2.操作步骤
         *      1.获取连接
         *      2.获取databasemetaData
         *      3.获取当前数据库中的所有表
         *      4.获取每个表中的所有字段
         *      5.封装到java对象中即可
         */
        public static List<Table> getDbInfo(DataBase db) throws  Exception {
            //1.获取连接
            Connection connection = getConnection(db);
            //2.获取元数据
            DatabaseMetaData metaData = connection.getMetaData();
            //3.获取当前数据库中的所有表
            ResultSet tables = metaData.getTables(null, null, "pe_permission", new String[]{"TABLE"});
     
            List<Table> list = new ArrayList<>();
     
            while (tables.next()) {
                Table tab = new Table();
                //i.表名
                String tableName = tables.getString("TABLE_NAME"); //bs_user  User
                //ii.类名
                String className = removePrefix(tableName);
                //iii.描述
                String remarks = tables.getString("REMARKS");
                //iiii.主键
                ResultSet primaryKeys = metaData.getPrimaryKeys(null, null, tableName);
                String keys = "";
                while (primaryKeys.next()) {
                    String keyname = primaryKeys.getString("COLUMN_NAME");
                    keys += keyname+",";
                }
                tab.setName(tableName);
                tab.setName2(className);
                tab.setComment(remarks);
                tab.setKey(keys);
                //处理表中的所有字段
     
                ResultSet columns = metaData.getColumns(null, null, tableName, null);
     
                List <Column> columnList = new ArrayList<>();
     
                while (columns.next()) {
                    Column cn = new Column();
                    //构造Column对象
                    //列名称
                    String columnName = columns.getString("COLUMN_NAME"); //user_id  userId , create_time createTime
                    cn.setColumnName(columnName);
                    //属性名
                    String attName = StringUtils.toJavaVariableName(columnName);
                    cn.setColumnName2(attName);
                    //java类型和数据库类型
                    String dbType = columns.getString("TYPE_NAME");//VARCHAR,DATETIME
                    cn.setColumnDbType(dbType);
                    String javaType = PropertiesUtils.customMap.get(dbType);
                    cn.setColumnType(javaType);
                    //备注
                    String columnRemark = columns.getString("REMARKS");//VARCHAR,DATETIME
                    cn.setColumnComment(columnRemark);
                    //是否主键
                    String pri = null;
                    if(StringUtils.contains(columnName ,keys.split(","))) {
                        pri = "PRI";
                    }
                    cn.setColumnKey(pri);
                    columnList.add(cn);
                }
                columns.close();
                tab.setColumns(columnList);
                list.add(tab);
            }
            tables.close();
            connection.close();
            return list;
        }
     
        public static String removePrefix(String tableName) {
            String prefix = PropertiesUtils.customMap.get("tableRemovePrefixes");
            //bs_,     tb_    , co_    ,
            String temp = tableName;  //bs_user
            for(String pf : prefix.split(",")) {
                temp = StringUtils.removePrefix(temp,pf,true);
            }
            //temp = user
            return StringUtils.makeAllWordFirstLetterUpperCase(temp);
        }
     
        public static void main(String[] args) throws Exception {
            DataBase db = new DataBase("MYSQL","ihrm");
            db.setUserName("root");
            db.setPassWord("111111");
     
            List<Table> dbInfo = DataBaseUtils.getDbInfo(db);
            for (Table table : dbInfo) {
                List<Column> columns = table.getColumns();
                for (Column column : columns) {
                    System.out.println(column);
                }
            }
        }
    }
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202501/17376868448221.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者