Java

Contents

1 동적 클래스 로딩
2 클래스가 어떤 리소스에서 로드되었는지 확인
3 classpath 에서 리소스 읽어들이기
4 System.in에서 키보드 입력을 받을때 에코되는 문자를 안보이게
5 SimpleDateFormat, Calendar : 문자열에서 날짜 파싱후 날짜연산 후 다시 스트링으로 포매팅

3 classpath 에서 리소스 읽어들이기 #

inputStream = Thread.currentThread().getContextClassLoader()
  .getResourceAsStream("dir/test.xml");

4 System.in에서 키보드 입력을 받을때 에코되는 문자를 안보이게 #

java 커맨드라인(command line)기반 응용프로그램에서 키보드 입력을 받을때 입력하는 문자가 항상 에코되어 보여진다. 문제는 암호같은걸 받을때 이를 마스킹(masking)해주거나 지워줘야하는데 해결책이 별로 없다. 아래와 같은 쓰레드를 이용한 대안이 있다.

# 쓰레드
		// 키보드 입력시 에코문자를 지워줄 쓰레드
		this.threadKeyInEchoEraser = new Thread(new Runnable(){
			public void run()
			{
				while(shouldRunKeyInEchoEraserThread){
					System.out.print("\010*");
					try{
						Thread.sleep(1);
					}
					catch(InterruptedException ie){
						ie.printStackTrace();
					}
				}	
			}
		});
		this.shouldRunKeyInEchoEraserThread = true;
		this.threadKeyInEchoEraser.start();

# 입력받는 부분
		
		BufferedReader br 
			= new BufferedReader(new InputStreamReader(System.in));
		String password = br.readLine();
		
		// stop keyinEchoEraser thread
		this.shouldRunKeyInEchoEraserThread = false;
		
		System.out.println("passwd = "+password);

5 SimpleDateFormat, Calendar : 문자열에서 날짜 파싱후 날짜연산 후 다시 스트링으로 포매팅 #

import java.text.ParseException;
import java.text.SimpleDateFormat;
        String orgStr = "20060501";
        System.out.println(orgStr);
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    	Date dt = null;
    	try{
    		dt = sdf.parse(orgStr);
    	}
    	catch(ParseException pe){
    		pe.printStackTrace();
    	}
    	
    	Calendar cal = Calendar.getInstance();
    	cal.setTime(dt);
    	
    	System.out.println(cal.getTime());
    	cal.add(Calendar.MONTH, 2);
    	System.out.println(cal.getTime());
    	
    	String str = sdf.format(cal.getTime());
    	System.out.println(str);
  • 결과
20060501
Mon May 01 00:00:00 KST 2006
Sat Jul 01 00:00:00 KST 2006
20060701
Valid XHTML 1.0! Valid CSS! powered by MoniWiki
last modified 2009-12-02 19:33:23
Processing time 0.0112 sec