2009년 10월 27일 화요일

[Java] 임의의 문자 생성기- 알파벳과 숫자로 된 임의의 키나 문자 생성기(Random letter generator)

가끔 임의의 키를 생성할 필요가 있다.
그럴땐 아래의 코드를 사용하면 쉽게 처리할 수 있을 것이다.



package random.string;

import java.util.Random;

public class RandomString {
public RandomString() {
}
public static void main(String args[]) {
RandomString rs=new RandomString();
String randomKey=rs.generateData(20);
System.out.println(randomKey);
}
final String dummyString="1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijlmnopqrstuvwxyz";
final Random random=new Random();
public String generateData(int loopCount) {
// char 48=0 65=A 90=Z 97=a 122=z
StringBuilder tempBuilder=new StringBuilder(100);
int randomInt;
char tempChar;
for(int loop=0;loop<loopCount;loop++) {
randomInt=random.nextInt(61);
tempChar=dummyString.charAt(randomInt);
tempBuilder.append(tempChar);
}
//System.out.println(tempBuffer);
return tempBuilder.toString();
}
}


[자바 문자 입력 받기] Java Console

JDK 6.0 이상부터 추가된 클래스중에 Console이라는 클래스가 있다.
이제부터는 자바 커맨드 창에서 문자를 입력받을때,
복잡하게 stream을 구현할 필요가 없어 졌다.



package console;

import java.io.Console;

public class ConsoleTest {
public static void main(String args[]) {
Console console=System.console();
if(console!=null) {
String id=console.readLine("%s","ID:");
char[] password=console.readPassword("%s", "Password:");
if(id!=null & password!=null) {
System.out.println("ID="+id);
System.out.println("PW="+new String(password));
}
} else {
System.out.println("Console is null");
}
}
}