1. 程式人生 > 實用技巧 >常用的功能的程式碼片段

常用的功能的程式碼片段

1.獲取字串中某個字元段第幾次出現的位置:例如拿url中第三個‘/’的位置,並把該位置(包含該位置)後的字串輸出:

@Test
    public void tetssss()
    {
        System.out.print(testss("http://localhost:8080/ylitsm/androidpublic/alogin.do?","/",3));
    }
    
    /**
     * 
     *author:cwy
     *說明:
     *引數:
     * @param string----------字串
     * @param sub------------子字串
     * @param index----------第幾個(從1開始)
     * @return
     
*/ public String testss(String string,String sub,int index) { //這裡是獲取"/"符號的位置 Matcher slashMatcher = Pattern.compile(sub).matcher(string); int mIdx = 0; while(slashMatcher.find()) { mIdx++; //當"/"符號第三次出現的位置 if(mIdx == index){
break; } } return string.substring(slashMatcher.start())+""; }

2.根據兩個ip,開始ip,結束ip,算出他們中間存在的ip

/** 
     * @author cwy 
     * @date 2017-1-4 下午8:54:22
     * @version 版本號碼
     * @TODO 描述:根據IP起始地址和結尾地址計算兩者之間的地址
     * ipfrom---------開始ip
     * ipto-----------結束ip
     */
public static Object[] GET_IP_ARR(String ipfrom, String ipto) { List<String> ips = new ArrayList<String>(); String[] ipfromd = ipfrom.split("\\."); String[] iptod = ipto.split("\\."); int[] int_ipf = new int[4]; int[] int_ipt = new int[4]; for (int i = 0; i < 4; i++) { int_ipf[i] = Integer.parseInt(ipfromd[i]); int_ipt[i] = Integer.parseInt(iptod[i]); } for (int A = int_ipf[0]; A <= int_ipt[0]; A++) { for (int B = (A == int_ipf[0] ? int_ipf[1] : 0); B <= (A == int_ipt[0] ? int_ipt[1] : 255); B++) { for (int C = (B == int_ipf[1] ? int_ipf[2] : 0); C <= (B == int_ipt[1] ? int_ipt[2] : 255); C++) { for (int D = (C == int_ipf[2] ? int_ipf[3] : 0); D <= (C == int_ipt[2] ? int_ipt[3] : 255); D++) { ips.add(new String(A + "." + B + "." + C + "." + D)); } } } } return ips.toArray(); } public static void main(String[] args) { Object[] str=IpUtil.GET_IP_ARR("192.168.1.1","192.168.1.255"); for(int i=0;i<str.length;i++) { System.out.println(str[i].toString()); } }

3.從資料庫拿資料時,將帶下劃線的欄位去掉,並把下劃線後的首字母變成大寫。

  commons.lang3包很好用

1.先全部變成小寫字元,2,進行變化

String property = convertProperty(StringUtils.lowerCase(columnLabel)); // 屬性名稱(小寫);
/**
     * 格式資料庫欄位,把下劃線去掉並緊跟首字母大寫,轉換為物件屬性
     * 
     * @param srcStr
     * @return
     */
    private static String convertProperty(String srcStr) {
        String property = "";
        if (srcStr.indexOf("_") > -1) { // 存在下劃線
            StringBuilder sb = new StringBuilder();
 
            String[] strs = srcStr.split("_");
            sb.append(strs[0]);
            for (int i = 1; i < strs.length; i++) {
                sb.append(StringUtils.capitalize(strs[i])); // 首字母大寫
            }
            property = sb.toString();
        } else {
            property = srcStr;
        }
        return property;
    }

4.生成首字母大寫的set,或get方法:

    /**
     * 首字母大寫並生成setXX方法
     * 
     * @param srcStr
     * @return
     */
    private static String setFirstCharacterToUpper(String srcStr) {
        String setMethod = "set" + StringUtils.capitalize(srcStr); // 首字母大寫
        return setMethod;
    }

5.判斷請求來自手機還是網頁

    /** 
     * @author cwy 
     * @date 2017-1-13 上午9:36:54
     * @version 版本號碼
     * @TODO 描述:判斷裝置屬於手機還是網頁
     */
    
    
    public static boolean  isMobileDevice(String requestHeader){
        /**
         * android : 所有android裝置
         * mac os : iphone ipad
         * windows phone:Nokia等windows系統的手機
         */
        String[] deviceArray = new String[]{"android","mac os","windows phone"};
        if(requestHeader == null)
            return false;
        requestHeader = requestHeader.toLowerCase();
        for(int i=0;i<deviceArray.length;i++){
            if(requestHeader.indexOf(deviceArray[i])>0){
                return true;
            }
        }
        return false;
}

6.按位數生成隨機數字,在生成工單的時候很好用

/**
     * 按位數生成字串
     * 
     * @param charCount
     *            位數
     * @return
     */
    public static String getRandNum(int charCount) {
        String charValue = "";
        for (int i = 0; i < charCount; i++) {
            char c = (char) (randomInt() + '0');
            charValue += String.valueOf(c);
        }
        return charValue;
    }
    /**
     * 隨機生成0~9之間數字
     */
    private static int randomInt() {
        Random r = new Random();
        int num = r.nextInt(10); // 隨機生成0~9之間數字
        return num;
    }

7.讀取Properties檔案工具類:

public class PropertiesUtil {
 
    private static Logger logger = LogManager.getLogger(PropertiesUtil.class);
 
    private static Properties prop = null;
 
    private PropertiesUtil() {
    }
 
    static {
        prop = new Properties();
        InputStream in = PropertiesUtil.class.getResourceAsStream("/properties/Prop.properties"); // 從根目錄下讀檔案
        try {
            prop.load(in);
        } catch (IOException e) {
            logger.debug("初始化properties檔案錯誤......");
            e.printStackTrace();
        }
    }
 
    /**
     * 獲取值
     * 
     * @param key
     * @return
     */
    public static String get(String key) {
        String valString = prop.getProperty(key, "");
//        logger.debug("key:" + key + "      value:" + valString);
        return valString;
    }
 
    /**
     * 
     * 在記憶體中修改key對應的value值
     */
    public static void setProper(String key, String value) {
        prop.setProperty(key, value);
    }
 
}

8.二維陣列刪除指定名稱的列:

        /**
         * 
         * @param org  ---陣列
         * @param name ---指定要刪除列的名稱
         * @return 返回要刪除列的下標---------- 從0開始, -1表示找不到要刪除的列
         */
        public static int getCol(String org[][],String name)      
        {
            for(int i=0;i<org[0].length;i++)
            {
                if(org[0][i].equals(name))
                {
                    return i;
                }
            }
            return -1;
        }
        
        /**
         * 
         * @param org ---資料來源
         * @param name-----要刪除的列的名稱
         * @return 刪除列後的二維陣列
         */
        public static  String[][] delCol(String org[][],String name)
        {
            String target[][]=new String[org.length][org[0].length-1];
            int lie=getCol(org,name);
            if(lie==-1)
            {
                return org;
            }
            else
            {
                for(;lie<org[0].length-1;lie++)              //刪除列,將列右邊的資料左移動
                {
                    for(int i=0;i<org.length;i++)
                    {
                        
                            org[i][lie]=org[i][lie+1];   
                    }
                }
            }
            
            for(int k=0;k<org.length;k++)            //對目標陣列進行賦值
            {
                
                for(int a=0;a<org[0].length-1;a++)
                {
                    target[k][a]=org[k][a];
                }
            }
            return target;
        }

9.刪除二維陣列指定行:

        /**
         * 
         * @param org------資料來源
         * @param name-------指定行名稱
         * @return
         */
        public static int getRow(String org[][],String name)      
        {
            for(int i=0;i<org.length;i++)
            {
                if(org[i][0].equals(name))
                {
                    return i;
                }
            }
            return -1;
        }
 
public static  String[][] delRow(String org[][],String name)
        {
            String target[][]=new String[org.length-1][org[0].length];
            int hang=getRow(org,name);
            if(hang==-1)
            {
                return org;
            }
            else
            {
                for(;hang<org.length-1;hang++)              //刪除列,將行下邊的資料上移動
                {
                    for(int i=0;i<org[0].length;i++)
                    {
                        
                            org[hang][i]=org[hang+1][i];   
                    }
                }
            }
            
            for(int k=0;k<org.length-1;k++)            //對目標陣列進行賦值
            {
                
                for(int a=0;a<org[0].length;a++)
                {
                    target[k][a]=org[k][a];
                }
            }
            return target;
        }
        

Fping操作

根據IP獲取地址

根據IP/掩碼位獲取IP的起始範圍、IP總數、IP屬不屬於某個網段或者列印網段內所有的IP