Java

[Java] Random ID 생성하기(날짜/시간 X)

김먼저 2023. 6. 15. 09:30
public class GenerateRandomId {
    private static final String CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+-=[]{}|/";
    private static final int DEFAULT_LENGTH = 10;

    public String generateRandomString() {
        return generateRandomString(DEFAULT_LENGTH);
    }

    public String generateRandomString(int length) {
        StringBuilder sb = new StringBuilder(length);
        Random random = new SecureRandom();
        for (int i = 0; i < length; i++) {
            int randomIndex = random.nextInt(CHARACTERS.length());
            char randomChar = CHARACTERS.charAt(randomIndex);
            sb.append(randomChar);
        }
        return sb.toString();
    }
}

 

저장용 Class.

 

char단위로 설정 및 글자수도 설정이 가능.

 

더 좋은 코드가 있다면 댓글 부탁드려요~!