1. 程式人生 > >IP地址+時間戳對檔案進行重新命名

IP地址+時間戳對檔案進行重新命名

package com.xidian.bbs.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

public class IpTimeStamp {
    private SimpleDateFormat sim=null;//用來獲取時間
    private String ip=null;
    public IpTimeStamp(){
    }
    public IpTimeStamp(String ip){
        this.ip=ip;
    }
    public String getIpTimeRand(){
        StringBuffer sbf=new StringBuffer();
        if(this.ip!=null){
            String a[]=this.ip.split("\\.");                //根據點來拆分ip地址,但點要轉義
            for(int i=0;i<a.length;i++){
                sbf.append(this.addZero(a[i], 3));            //呼叫補零的方法,每塊ip不足三位的自動補足到三位
            }
            sbf.append(this.getTimeStamp());                //用this來呼叫外部的方法
            Random random=new Random();                        //要產生隨機數
            for(int i=0;i<3;i++){                            //產生三位隨機數
                sbf.append(random.nextInt(10));                //每位隨機數都不超過10
            }
        }
        return sbf.toString();
    }
    @SuppressWarnings("unused")
    private String getDate(){                                //關於日期與時間的實現
        this.sim=new SimpleDateFormat("yyyy-mm-dd hh:mm:ss.SSS");
        return this.sim.format(new Date());
    }
    private String getTimeStamp(){                            //返回時間戳
        this.sim=new SimpleDateFormat("yyyymmddhhmmssSSS");
        return this.sim.format(new Date());
    }
    private String addZero(String str,int len){                //自動補零的方法,引數為指定的字串和長度
        StringBuffer s=new StringBuffer();
        s.append(str);
        while(s.length()<len){
            s.insert(0,"0");                                //在零的位置上進行補零操作
        }
        return s.toString();
    }
    
    //做測試
    public static void main(String [] ary){
        IpTimeStamp IpTimeStamp=new IpTimeStamp("172.168.3.222");//呼叫有引數的構造方法
        System.out.println(IpTimeStamp.getIpTimeRand());
    }
}