티스토리 뷰

일을 하다보면 작성하기 귀찮은 코드들을 찾기 위해 구글링을 통하여 무한 복불을 한다. 랜덤 문자열 생성도 마찬가지로 이곳저곳 검색해서 많이 사용 했었는데, 간혹 특정한 문자 값들로 랜덤 문자열을 만들거나, 또는 랜덤 문자열에서 제외할 문자 값을 설정할 필요가 있어서 만들었다.

:: 사용법


String randStr;
// 숫자를 제외한 길이 32의 랜덤 문자열 생성.
randStr =  new RandomStringBuilder().
           putExcludedChar(RandomStringBuilder.NUMBER).
           setLength(32).build();
System.out.println(randStr);
     
// 알파벳으로 이루어진 길의 32의 랜덤 문자열 생성.
randStr =  new RandomStringBuilder().
           putLimitedChar(RandomStringBuilder.ALPHABET).
           setLength(32).build();
System.out.println(randStr);
     
// 대문자와 특수문자로 이루어져있고, ?.,&$/\"' 를 제외한 길이 32의 랜덤 문자열 생성.
randStr =  new RandomStringBuilder().
           putLimitedChar(RandomStringBuilder.ALPHABET_UPPER_CASE).
           putLimitedChar(RandomStringBuilder.SPECIAL).
           putExcludedChar("?.,&$/\\\"'").
           setLength(32).build();
System.out.println(randStr);


결과 
   
Qs1Nyp4CA(oo-GbUPNvZ~eO=yDgHKKev 
aCDjMUySCJjKieiymEoiooBYYKKitIgq       
R>D=HJ[]P#I-]|@~FP%-Q:M}`DN_~KK=     


::: RandomStringBuilder 클래스 내부

public
class RandomStringBuilder {
     
    public static final String NUMBER = "0123456789";
    public static final String ALPHABET_LOWER_CASE = "abcdefghijkmnlopqrstuvwxyz";
    public static final String ALPHABET_UPPER_CASE = "ABCDEFGHIJKMNLOPQRSTUVWXYZ";
    public static final String ALPHABET = ALPHABET_LOWER_CASE + ALPHABET_UPPER_CASE;
    public static final String SPECIAL = "~!@#$%^&*()_+{}|\\\"`;:'<>?,./=-[]";
     
     
    private HashSet<character> mExcludedCharSet = new HashSet<character>();
    private ArrayList<character> mLimitCharList = new ArrayList<character>();
             
    int mLength = 32;
     
    public String build() {
        return generateRandomString(mLength);
    }
     
    public RandomStringBuilder setLength(int length) {
        mLength = length;
        return this;
    }
     
    public int getLength() {
        return mLength;
    }
     
    public RandomStringBuilder putExcludedChar(char excluded) {
        mExcludedCharSet.add(excluded);
        return this;
    }
     
    public RandomStringBuilder putExcludedChar(char[] excludedList) {
        for(char excluded : excludedList)
                putExcludedChar(excluded);
        return this;
    }
     
    public RandomStringBuilder putExcludedChar(String excluded) {
                putExcludedChar(excluded.toCharArray());
        return this;
    }
     
    public RandomStringBuilder putLimitedChar(char limited) {
        mLimitCharList.add(limited);
        return this;
    }
     
    public RandomStringBuilder putLimitedChar(char[] limitedList) {
        for(char limited : limitedList)
                putLimitedChar(limited);
        return this;
    }
     
    public RandomStringBuilder putLimitedChar(String limited) {
        putLimitedChar(limited.toCharArray());
        return this;
    }
     
    public boolean removeExcluded(char excluded) {
        return mExcludedCharSet.remove(excluded);
    }
     
    public boolean removeLimitedChar(char limited) {
        return mLimitCharList.remove((Character)limited);
    }
     
    public void clearExcluded() {
        mExcludedCharSet.clear();
    }
    public void clearLimited() {
        mLimitCharList.clear();
    }
     
     
    /**
     * 랜덤 문자열 생성.
     * @param length 문자열 길이
     * @return 랜덤 문자열
     */
    public String generateRandomString(int length) {
        boolean runExcludeChar = !isExcludedCharInLimitedChar();           
        StringBuffer strBuffer = new StringBuffer(length);
        Random rand = new Random(System.nanoTime());
        for(int i = 0; i < length; ++i ) {
            char randomChar = makeChar(rand);
            if(runExcludeChar)
                randomChar = excludeChar(rand, randomChar);
            strBuffer.append(randomChar);
        }
        return strBuffer.toString();
    }
     
    private boolean isExcludedCharInLimitedChar() {
        return mExcludedCharSet.containsAll(mLimitCharList);
    }
     
    private char excludeChar(Random rand, char arg) {
        while(mExcludedCharSet.contains(arg)) {
            arg = makeChar(rand);
        }
        return arg;
    }
    private char makeChar(Random rand) {
        if(mLimitCharList.isEmpty())
            return (char)(rand.nextInt(94) + 33);
        else
            return mLimitCharList.get(rand.nextInt(mLimitCharList.size()));
    }
}



댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함