'java'에 해당되는 글 40건

  1. 2013.07.29 Thread
  2. 2013.07.29 Iterator
  3. 2013.07.26 Properties
  4. 2013.07.25 Arrays
  5. 2013.07.25 File
  6. 2013.07.25 Class
  7. 2013.07.25 날짜관련
  8. 2013.07.25 Date, SimpleDateFormat
  9. 2013.07.25 Calendar, GregorianCalendar
  10. 2013.07.25 byte[] ↔ String
2013. 7. 29. 18:05

thread : 프로그램의 흐름

프로그램을 실행하면, main()메서드가  호출되어 하나의 흐름인 메인 스레드가 시작된다.


흐름이 하나밖에 없는 프로그램을 싱글 스레드.

Java에서는 흐름을 여러개 만들어 동시에 실행할 수 있는데 이처럼 흐름이 여러개 있는 프로그램을 멀티 스레드라 한다.





Thread를 생성하는 방법은 두가지가 있는데 runnable 인터페이스를 implements 하거나
Thread 클래스를 extends하는 방법이 있다

Thread 클래스
Java에서 멀티 스레드를 수행하기 위해서는 Thread클래스를 이용하여 새로운 스레드를 만들어줘야한다.
스레드를 만들기 위해서는 우선 Thread클래스를 상속받는 클래스를 작성하고 run()메소드를 오버라이딩 해준다.
그리고 그 안에 처리할 내용을 기술한다.



 class HelloThread extends Thread(){
public void run(){   // run 메소드 실행

}
}

스레드의 작성과 실행은 다음과 같이 한다.


HelloThread h = new HelloThread();
h.start();       // start()메소드 실행 시킨다

package thread;

public class tickTack extends Thread{
    private String word;
    private int time;
    private int count;
    
    public tickTack(String w, int t, int c) {
        word = w;
        time = t;
        count = c;
    }
    
    @Override
    public void run() {       // 스레드 클래스의 run 메소드를 오버라이딩한다.
        for (int i = 0; i < count; i++) {
            System.out.println(word);
            try {
                Thread.sleep(time);
            } catch (Exception e) {

            }
            
        }
    }

    
    public static void main(String[] args){
        tickTack tt = new tickTack("안녕", 1000, 4);   // 생성자를 사용해 호출,  안녕을 1000만큼 sleep, 4번 출력
        tickTack tt2 = new tickTack("Hello", 1000, 3); // 생성자를 사용해 호출,  Hello를 1000만큼 sleep, 3번 출력
        tickTack tt3 = new tickTack("하이", 1000, 3);  // 생성자를 사용해 호출,  하이를 1000만큼 sleep, 3번 출력
        
        tt.start();
        try {
            Thread.sleep(500);        // 0.5 지연
        } catch (Exception e) {
            // TODO: handle exception
        }
        tt2.start();
        try {
            Thread.sleep(500);        // 0.5 지연
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        tt3.start();
        
    }
    
    
}



안녕

Hello
하이
안녕
Hello
하이
안녕
Hello
하이

안녕

 

'java' 카테고리의 다른 글

Iterator  (0) 2013.07.29
Properties  (0) 2013.07.26
Arrays  (0) 2013.07.25
File  (0) 2013.07.25
Class  (0) 2013.07.25
Posted by 1+1은?
2013. 7. 29. 11:40

Interface Iterator<E>



다음은 Iterator 의 실제 소스다.

1
2
3
4
5
public interface Iterator<E> {
    boolean hasNext();
    E next();
    void remove();
}


List 는 인덱스가 존재하여 단순한 for문으로도 객체의 데이터를 가져올 수 있으며

향상된 포문문을 사용하면 Set의 데이터도 가져오는게 가능하다.


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
32
ArrayList<String> list = new ArrayList<String>();
list.add("하나");
list.add("둘");
list.add("셋");
 
for(String ele : list) {
    System.out.println(ele);
}
 
for(int loop=0; loop<list.size(); loop++) {
    System.out.println(list.get(loop));
}
 
HashSet<Integer> set = new HashSet<>();
set.add(1);
set.add(3);
set.add(2);
 
for(Integer ele : set) {
    System.out.println(ele);
}
 
 
하나
하나
1
2
3


List, Set 모두 Iterator를 구현해 놓은 클래스이기 때문에 향상된 포문을 사용할 수 있는 것이다.

하지만 Map은 인덱스도 없고 Iterator 구현도 없다. 어떻게 해야 할까



● boolean hasNext() : Iterator 객체가 다음요소를 소유하는지 여부를 불리언으로 리턴. 

● E next() : 다음요소를 리턴.

● void remove() : 컬렉션에서 Iterator 의해 반환된 마지막 요소를 제거. 


우선 아래는 List와 Set에서 Iterator를 사용하는 예제다.

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
32
ArrayList<String> list = new ArrayList<String>();
list.add("하나");
list.add("둘");
list.add("셋");
 
Iterator<String> it = list.iterator();
 
while(it.hasNext()) { //Iterator 객체에 다음 데이터가 있으면 true
    String ele = it.next(); //다음 데이터를 리턴
    System.out.println(ele);
}
 
 
HashSet<Integer> set = new HashSet<>();
set.add(1);
set.add(3);
set.add(2);
 
Iterator<Integer> it2 = set.iterator();
 
while(it2.hasNext()) {
    int ele = it2.next();
    System.out.println(ele);
}
 
 
하나
1
2
3


Map에선 다음과 같이 사용한다.

1
2
3
4
5
ArrayList<String> list = new ArrayList<String>();
HashMap<String, Integer> map = new HashMap<>();
map.put("일공일", 101);
map.put("이공이", 202);
map.put("삼공삼", 303);


여기서 keySet() 메서드로 key값을 Set 컬렉션으로 추출한다.

1
2
3
4
5
Set<String> set = map.keySet();
System.out.println(set);
 
 
[삼공삼, 일공일, 이공이]


이제 Iterator를 사용하여 value를 가져올 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
Iterator<String> it = set.iterator();
 
while(it.hasNext()) {
    String key = it.next();
    int value = map.get(key);
    System.out.println(key + " : " + value);
}
 
 
삼공삼 : 303
일공일 : 101
이공이 : 202


번거롭다면 향상된 포문을 써도 된다. (향상된 포문은 Java 5.0 이상에서만 사용가능)

1
2
3
4
5
6
7
8
9
10
11
Iterator<String> it = set.iterator();
 
for(String key : set) {
    int value = map.get(key);
    System.out.println(key + " : " + value);
}
 
 
삼공삼 : 303
일공일 : 101
이공이 : 202



● 완성 구문

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import java.util.HashMap;
import java.util.Iterator;
 
public class LogicTest {
    public static void main(String[] args) throws Exception {
    
        HashMap<String, Integer> map = new HashMap<>();
        map.put("일공일", 101);
        map.put("이공이", 202);
        map.put("삼공삼", 303);
                 
        Iterator<String> it = map.keySet().iterator();       
         
        while(it.hasNext()) {
            String key = it.next();
            int value = map.get(key);
            System.out.println(key + " : " + value);
        }
    }
}


'java' 카테고리의 다른 글

Thread  (0) 2013.07.29
Properties  (0) 2013.07.26
Arrays  (0) 2013.07.25
File  (0) 2013.07.25
Class  (0) 2013.07.25
Posted by 1+1은?
2013. 7. 26. 09:48

Class Properties

java.lang.Object

java.util.Dictionary<K,V>

java.util.Hashtable<Object,Object>

java.util.Properties




Map 클래스를 상속받은 컬렉션의 일종. Key와 Value를 갖는다.


1
2
3
4
5
6
7
8
9
10
11
Properties prop = new Properties();
prop.put("서울의수도", "서울의수도가어디있어");
System.out.println(prop);
 
Map<String, String> map = new HashMap<>();
map.put("한국의수도", "서울");
System.out.println(map);
 
 
{서울의수도=서울의수도가어디있어}
{한국의수도=서울}

해쉬맵과 흡사하나 파일입출력 기능을 지원하며 자료형은 String만 가능


● void store(OutputStream out, String comments)

● void store(Writer writer, String comments)

객체에 저장된 데이터를 파일로 출력

1
2
3
4
5
6
7
8
9
10
11
12
13
Properties prop = new Properties();
prop.put("서울의수도", "서울의수도가어디있어");
 
try {
     
    FileOutputStream fos = new FileOutputStream("d:\\web\\work\\test\\data\\PropTest.propfile");
    prop.store(fos, "코멘트테스트");
    fos.close();
     
    //경로를 명시하지 않으면 루트경로(워크스페이스\프로젝트명)에 저장된다
 
} catch (Exception e) {
}




● void load(InputStream inStream)

● void load(Reader reader)

맵 형태로 저장된 파일의 아스키코드를 불러와 Properties 객체에 저장

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Properties prop = new Properties();
 
try {
    FileInputStream fis = new FileInputStream("data\\PropTest.propfile");
    prop.load(fis);
    fis.close();
} catch (Exception e) {
}
 
prop.list(System.out);
 
System.out.println("\n" + prop.getProperty("서울의수도"));
 
 
-- listing properties --
서울의수도=서울의수도가어디있어
 
서울의수도가어디있어



Properties 클래스는 HashMap 과 마찬가지로 서수가 없기 때문에 각각의 값을 반복문으로 처리하려면 Iterator 를 이용한다.


예를 들어 다음과 같을때

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Properties prop = new Properties();
prop.setProperty("서울", "매우많음");
prop.setProperty("대전", "조금많음");
prop.setProperty("인천", "많음");
prop.setProperty("공주", "10만은 되려나?");
 
try {
    FileOutputStream fos = new FileOutputStream("data\\PropTest.propfile");
    prop.store(fos, "코멘트는 중요치 않아요~");
    fos.close();
     
    FileInputStream fis = new FileInputStream("data\\PropTest.propfile");
    prop.load(fis);
    fis.close();
} catch (Exception e) {
}
 
System.out.println(prop.values());
 
 
[많음, 매우많음, 조금많음, 10만은 되려나?]

여기서 이터레이터로 맵의 값을 가져오는 방법은


● Set<K> keySet() : Returns a Set view of the keys contained in this map. (HashTable 클래스의 메서드를 상속받음)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
Iterator<Object> it = prop.keySet().iterator();
 
while(it.hasNext()) {
    String key = (String) it.next();
    String value = (String) prop.getProperty(key);
     
    System.out.println(key + " : " + value);
}
 
 
인천 : 많음
서울 : 매우많음
대전 : 조금많음
공주 : 10만은 되려나?



아래처럼 아스키코드가 아니어도 인코딩처리 없이 사용할 수 있다.

("=" 를 기준 좌측이 key, 우측은 value)



※ 주의 : 한글은 불가능


1
2
3
4
5
6
7
8
9
10
11
12
13
Properties prop = new Properties();
 
try {
    FileInputStream fis = new FileInputStream("data\\PropTest.propfile");
    prop.load(fis);
    fis.close();
} catch (Exception e) {
}
 
System.out.println(prop);
 
 
{bbs.do=com.mvc.bbs.BoardAction, ÇѱÛ=ÀÌ µÇ·Á³ª?, guest.do=com.mvc.guest.GuestAction}


이 구문은 Servlet MVC2 패턴을 구현할 때 사용되니 숙지할 것.



'java' 카테고리의 다른 글

Thread  (0) 2013.07.29
Iterator  (0) 2013.07.29
Arrays  (0) 2013.07.25
File  (0) 2013.07.25
Class  (0) 2013.07.25
Posted by 1+1은?
2013. 7. 25. 16:54

Class Arrays

java.lang.Object

java.util.Arrays

 

배열의 조작을 지원하는 클래스.

검색이나 정렬 등을 간단하게 할 수 있다.

 

 

● static void sort(int[] a) : 배열의 값들을 오름차순으로 정렬

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int[] ns = { 3, 5, 1, 6, 8, 10, 2 };
 
for (int loop = 0; loop < ns.length; loop++) {
    System.out.print(ns[loop] + " ");
}
System.out.println();
 
Arrays.sort(ns); // Arrays의 메서드 대부분은 스태틱으로 선언없이 사용한다.
 
for (int loop = 0; loop < ns.length; loop++) {
    System.out.print(ns[loop] + " ");
}
 
 
3 5 1 6 8 10 2
1 2 3 5 6 8 10

 

 

● static void sort(int[] a, int fromIndex, int toIndex) : 범위를 지정해 오름차순으로 정렬

Arrays.sort(ns, A, B) : A=시작인덱스, B=종료 인덱스

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int[] ns = { 3, 5, 1, 6, 8, 10, 2 };
 
for (int loop = 0; loop < ns.length; loop++) {
    System.out.print(ns[loop] + " ");
}
System.out.println();
 
Arrays.sort(ns, 3, ns.length); //인덱스 3(네번째) 부터 끝까지 정렬
 
for (int loop = 0; loop < ns.length; loop++) {
    System.out.print(ns[loop] + " ");
}
 
 
3 5 1 6 8 10 2
3 5 1 2 6 8 10


'java' 카테고리의 다른 글

Iterator  (0) 2013.07.29
Properties  (0) 2013.07.26
File  (0) 2013.07.25
Class  (0) 2013.07.25
날짜관련  (0) 2013.07.25
Posted by 1+1은?
2013. 7. 25. 16:54

Class File

java.lang.Object

java.io.File

 

 

 

● boolean isFile() : 파일인지 검사

 

 boolean isDirectory() : 디렉토리인지 검사

 

 long lastModified() : 마지막 수정일 리턴

 

 boolean canRead() : 읽기가능 검사

 

 boolean canWrite() : 쓰기가능 검사

 

 boolean isHidden() : 숨김파일인지 검사

 

 String getPath() : 상대경로

 

 String getAbsolutePath() : 절대경로

 

 String getName() : 파일이름 리턴

 

 Long length() : 파일의 바이트 크기 리턴

 

 boolean delete() : 파일삭제 //폴더를 대상으로 할 경우 자식파일이나 폴더가 존재하면 삭제할 수 없다.

 

 boolean renameTo(File destination)

 

1
2
3
4
File file = new File("d:\\AAA\\aaa.txt"); //원본파일
File dest = new File("d:\\BBB\\aaa.txt"); //이동할 경로
 
file.renameTo(dest);

 

 

 File[] listFiles() : 해당 경로의 자식파일|폴더를 File배열로 리턴

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
String path = "D:\\B_JAVA\\Example";
File dir = new File(path);
         
if (dir.exists())
{
File[] list = dir.listFiles();  //자식디렉토리 목록 & 파일목록
 
for (File i : list)
{
    if (list[i].isDirectory())
        System.out.prinln("폴더 : " +  list[i].getName());
 
        if (i.isFile())
        System.out.prinln("파일 : " +  i.getName());
}
}

 

 

● boolean mkdir() : 폴더 생성

 

 

1
2
3
4
5
6
File dir = new File("D:\\CCC");
 
if (!dir.exists()) { //존재하지 않으면
 
    dir.mkdir(); //생성
}


'java' 카테고리의 다른 글

Properties  (0) 2013.07.26
Arrays  (0) 2013.07.25
Class  (0) 2013.07.25
날짜관련  (0) 2013.07.25
Date, SimpleDateFormat  (0) 2013.07.25
Posted by 1+1은?
2013. 7. 25. 16:53

Class Class<T>

java.lang.Object

java.lang.Class<T>

 

 

 Class<T> 클래스는 특정 클래스나 인터페이스에 관한 정보를 검색할 수 있는 메소드를 포함하고 있다.

T는 이 Class 객체에 의해 모델화 되는 클래스의 형태로 예를 들어, String.class 의 형태는 Class<String>이다. 

모델화 되는 클래스가 명확하지 않는 경우 Class<?>를 사용한다.

 

 

● static Class<?> forName(String className) 

 : Returns the Class object associated with the class or interface with the given string name.

● static Class<?> forName(String name, boolean initialize, ClassLoader loader) 

 : Returns the Class object associated with the class or interface with the given string name, using the given class loader.

● T newInstance() : Creates a new instance of the class represented by this Class object.

new 연산자를 사용하지 않고도 원하는 클래스의 객체생성이 가능하다.

 

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
package com.test;
  
public class LogicTest {
    public static void main(String[] args) throws Exception {
  
        Temp t = new Temp();
        t.showText();
  
        Temp t2 = (Temp) Class.forName("com.test.Temp").newInstance();
        t2.showText();
         
        Class<?> cls = Class.forName("com.test.Temp");
        Object ob = cls.newInstance();
        Temp t3 = (Temp) ob;
        t3.showText();
    }
}
  
class Temp {
    public void showText() {
        System.out.println("하이");
    }
}
 
 
하이
하이
하이

 

 

다음처럼 JDBC 커넥션 드라이버를 로딩할 때 사용하기도 한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
public static Connection getConnection() {
    String url="jdbc:oracle:thin:@220.76.176.66:1521:orcl", user="noritersand", pwd="java301$!";
    if(conn == null) {
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            conn = DriverManager.getConnection(url, user, pwd);
        } catch (Exception e) {
            System.out.println(e);
        }
    }
    return conn;
}

 

 

 

■ 클래스의 정보 구하기

 

1
2
3
4
5
6
7
8
Class<?> cls = Class.forName("java.lang.String");
System.out.println("클래스가 갖고 있는 메소드");
 
Method[] m = cls.getMethods();
 
for(Method mm : m) {
    System.out.println(mm); //해당클래스의 메소드를 출력할 수 있다.
}

 

 

 

■ Class의 forName()메서드로 객체생성

 

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package com.test;
 
import java.lang.reflect.Method;
 
public class LogicTest {
    public static void main(String[] args) throws Exception {
 
        // Demo7 d = new Demo7()
        Class<?> cls = Class.forName("com.test.Demo7");
 
        Object ob = cls.newInstance(); // 객체생성
 
        Demo7 d = (Demo7) ob;
        d.setName("자바");
        d.write();
 
        // 메서드 정의
        Method m1 = cls.getDeclaredMethod("add", new Class[] { int.class, int.class });
        Method m2 = cls.getDeclaredMethod("plus", new Class[] { Integer.class, Integer.class });
        Method m3 = cls.getDeclaredMethod("print", new Class[] { String.class, int.class });
        Method m4 = cls.getDeclaredMethod("write", null);
 
        // 메서드 호출
        Object o1 = m1.invoke(ob, new Object[] { 10, 20 });
        System.out.println(o1);
 
        // 메서드 호출2
        m3.invoke(ob, new Object[] { "합 : ", o1 });
    }
}
 
class Demo7 {
    private String name;
 
    public void setName(String name) {
        this.name = name;
    }
 
    public void write() {
        System.out.println(name);
    }
 
    public int add(int a, int b) {
        return a + b;
    }
 
    public Integer plus(Integer a, Integer b) {
        return a + b;
    }
 
    public void print(String title, int a) {
        System.out.println(title + a);
    }
}

 

 

 

'java' 카테고리의 다른 글

Arrays  (0) 2013.07.25
File  (0) 2013.07.25
날짜관련  (0) 2013.07.25
Date, SimpleDateFormat  (0) 2013.07.25
Calendar, GregorianCalendar  (0) 2013.07.25
Posted by 1+1은?
2013. 7. 25. 16:53

참고자료

Link - http://www.yunsobi.com/blog/325

 

 

 

■ 날짜 설정

● Date

 

1
2
3
4
5
SimpleDateFormat startFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); //24시간은 HH
Date day = startFormat.parse("2013-05-01 10:00");
 
System.out.println(day); //Mon Jul 01 10:00:00 KST 2013
System.out.println(startFormat.format(day)); //2013-07-01 10:00

 

 

● Calendar

 

1
2
3
4
5
6
Calendar cal = Calendar.getInstance();
//혹은 Calendar cal = new GregorianCalendar();
cal.set(2013, 01-1, 01, 10, 14); //월은 -1 주의
 
System.out.println(cal.getTime()); //Tue Jan 01 10:14:28 KST 2013
System.out.println(cal.getTime().getTime()); //1357002859406

 

 

 

 

■ 날짜 연산

● Date

 

1
2
3
4
5
6
SimpleDateFormat startFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date day = startFormat.parse("2013-07-01 10:00");
System.out.println(startFormat.format(day)); //2013-07-01 10:00
 
day.setTime(day.getTime() + (60*1000)*666); //666분 후
System.out.println(startFormat.format(day)); //2013-07-01 21:06

 

 

 

● Calendar

 

1
2
3
4
5
6
7
8
9
Calendar cal = Calendar.getInstance();
cal.set(2013, 01-1, 01, 10, 14);
System.out.println(cal.getTime()); //Tue Jan 01 10:14:16 KST 2013
 
cal.add(cal.MINUTE, 99); //99분 후
//미련한 방법 → cal.set(2013, 01-1, 01, 10, (cal.get(cal.MINUTE)+99));
System.out.println(cal.getTime()); //Tue Jan 01 11:53:12 KST 2013
 
System.out.println(format.format(cal.getTime())); //2013-01-01 11:53

 

 

■ 요일 구하기 (일:1 월:2 화:3 수:4 목:5 금:6 토:7)

● switch

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Calendar cal = Calendar.getInstance();
 
int dow = cal.get(cal.DAY_OF_WEEK);
switch (dow) {
case 1: day += "(" + "일" + ")"; break;
case 2: day += "(" + "월" + ")"; break;
case 3: day += "(" + "화" + ")"; break;
case 4: day += "(" + "목" + ")"; break;
case 5: day += "(" + "목" + ")"; break;
case 6: day += "(" + "금" + ")"; break;
case 7: day += "(" + "토" + ")"; break;
}
 
dayList.add(day);

 

 

● array

 

1
2
3
4
5
6
7
8
9
10
11
Calendar cal = Calendar.getInstance();
 
String[] dayOfWeek = {"토", "일", "월", "화", "수", "목", "금"};
String yo_il = dayOfWeek[cal.get(cal.DAY_OF_WEEK)];
 
System.out.println(yo_il); //목
 
cal.add(cal.DATE, 1); //하루 후
yo_il = dayOfWeek[cal.get(cal.DAY_OF_WEEK)];
 
System.out.println(yo_il); //금

 

 

● 오늘부터 1주일 사이의 요일 구하기

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
SimpleDateFormat format = new SimpleDateFormat("MM-dd");
Calendar cal = Calendar.getInstance();
List<String> dayList = new ArrayList<String>();
String day = "";
String yoil = "";
 
for(int i=0; i<7; i++)
{
    day = format.format(cal.getTime());
     
    String[] dayOfWeek = {"일", "월", "화", "수", "목", "금", "토"};
    yoil = dayOfWeek[cal.get(cal.DAY_OF_WEEK)-1];
 
    day += "(" + yoil + ")";
     
    dayList.add(day);
    cal.add(cal.DATE, 1);
}
 
System.out.println(dayList);
     //[05-02(목), 05-03(금), 05-04(토), 05-05(일), 05-06(월), 05-07(화), 05-08(수)]

 

 

 

'java' 카테고리의 다른 글

File  (0) 2013.07.25
Class  (0) 2013.07.25
Date, SimpleDateFormat  (0) 2013.07.25
Calendar, GregorianCalendar  (0) 2013.07.25
byte[] ↔ String  (0) 2013.07.25
Posted by 1+1은?
2013. 7. 25. 16:52
Class Date
java.lang.Object
java.util.Date

java.lang.Object
java.text.Format
java.text.DateFormat
java.text.SimpleDateFormat

 

 

날짜형 데이터타입을 지원하는 클래스

 

 

 Date 예제

 

1
2
3
4
5
Date now = new Date(); //현재날짜를 가져온다.
System.out.println(now); //Tue Feb 19 12:38:17 KST 2013
 
long dif = d2.getTime() - d1.getTime();
long dd = dif/(24*60*60*1000); //두 날짜의 차를 구해 일로 계산

 

 

 

■ SimpleDateFormat 예제

 

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
32
33
34
35
36
37
38
39
Calendar cal = Calendar.getInstance();
 
// 2013-02-19일 설정
cal.set(2013, 1, 19);
 
// 100일 후
cal.add(Calendar.DAY_OF_MONTH, 100);
cal.add(Calendar.DATE, 100);
String str = String.format("%tF", cal);
System.out.println("백일 후 : " + str);
;
 
String s = "2013-02-26";
String e = "2013-10-20";
 
try {
    // 텍스트를 날짜로 변환
    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
    Date d1 = sf.parse(s);
    Date d2 = sf.parse(e); // Date 형변환
 
    // 두날짜의 간격
    long dif = d2.getTime() - d1.getTime(); // 틱값으로 계산
    long dd = dif / (24 * 60 * 60 * 1000);
    System.out.println("두 날짜간 간격 : " + dd);
 
    // 시스템의 현재 날짜
    Date now = new Date();
    Calendar now2 = Calendar.getInstance();
     
    // Date를 문자열 형식으로 변환
    System.out.println(now);
 
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy년 MM월 dd일 hh:mm:ss");
    String ss = sdf.format(now);
    System.out.println("현재 날짜 시간 : " + ss);
 
} catch (Exception e2) {
}


'java' 카테고리의 다른 글

Class  (0) 2013.07.25
날짜관련  (0) 2013.07.25
Calendar, GregorianCalendar  (0) 2013.07.25
byte[] ↔ String  (0) 2013.07.25
byte  (0) 2013.07.25
Posted by 1+1은?
2013. 7. 25. 16:52

Class Calendar

java.lang.Object

java.util.Calendar

 

Class GregorianCalendar

java.lang.Object

java.util.Calendar

java.util.GregorianCalendar

 

 

Calendar클래스는 날짜와 시간을 객체 모델링 화 한 클래스로 년, 월, 일, 요일, 시, 분, 초까지의 시간과 날짜와 관련된 정보를 제공한다. 

Calendar는 추상 클래스로 객체생성은 불가능하며 실제적인 메소드 구현은 서브 클래스인 GregorianCalendar클래스에 정의되어 있다.

 

만약 시스템으로부터 현재 시스템 시간 정보를 얻기 위해서는 getInstance() 라는 정적 메소드를 이용하여 객체를 생성한다. 생성된 Calendar 클래스 객체는 시스템의 현재 날짜와 시간 정보를 가지며, 이 객체가 생성되면 갖고 있는 시간 정보들은 get() 메소드를 이용하여 쉽게 사용 할 수 있다. getInstance() 메소드는 내부적으로 GregorianCalendar 객체를 생성하여 돌려주므로 GregorianCalendar 객체를 직접 생성하여 시간 정보를 구할 수 있다.

 

기타 날짜 관련 클래스로 java.util.Date 가 있으나 국제화 기능과 함께 각종 부가 기능이 추가된

Calendar류의 클래스를 사용할 것을 권장 한다.

 

 

■ 현재시각 가져오기

 

 

1
2
Calendar rightNow = Calendar.getInstance();
// Calendar rightNow = new GregorianCalendar();

 

 

 

혹은

 

 

1
GregorianCalendar rightNow = new GregorianCalendar(); // 직접 그레고리언 캘런더 생성

 

 

 

1
2
3
System.out.println("오늘 날짜는 " + rightNow.get(Calendar.YEAR) + "년 "
        + (rightNow.get(Calendar.MONTH) - Calendar.JANUARY + 1) + "월 "
        + rightNow.get(Calendar.DATE) + "일 ");

 

 

 

■ GregorianCalendar 클래스의 주요 메소드

● public int get(int field)

 

field에 해당하는 날짜를 반환한다. field는 Calendar 클래스에서 정의된 상수이다.

예) get(Calendar.MONTH); //달력의 월(월-1)을 반환한다.

 

 public void set(int field, int value)

field에 해당하는 날짜를 value 값으로 바꾼다.

예) set(Calendar.YEAR, 2000) //달력의 년을 2000년으로 바꾼다.

 

 public final void set(int year, int month, int date)

 public final void set(int year, int month, int date, int hour, int minute)

 public final void set(int year, int month, int date, int hour, int minute, int second)

 : calendar의 날짜를 바꾼다.

 

 public void add(int field, int amount)

 : field에 해당하는 날짜를 amount 만큼 증가시킨다.

 

 void roll(int field, boolean up)

 void roll(int field, int amount) 

 : 날짜 정보를 변경한다.

※ add() 메소드는 일수나 월수를 더해서 그 값이 한 달이나 일 년의 범위를

넘어서면 월이나 연수를 증가시키지만 roll() 메소드는 날짜에 많은 수를 더해도 월이 바뀌지 않고

그 달의 처음으로 다시 되돌아가 계산한다.

 

 

■ Calendar 클래스의 주요 메소드 및 상수

◆ 메소드

● static Calendar getInstance()

 : 현재 시스템의 시간 정보를 얻는 Calendar 클래스 객체를 생성한다.

 

● getActualMaximum

 : 해당 월의 마지막일 → int endDays = cal.getActualMaximum(Calendar.DATE);

 

◆ 상수

● YEAR, MONTH, DATE, HOUR, MINUTE, SECOND, MILLISECOND

년, 월, 일, 시, 분, 초, 1/1000초를 나타낸다.

 

● JANUARY(=0), FEBRUARY(=1), MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER(=11)

 : 1월 ~ 12월을 차례로 나타낸다. 주의할 점은 0부터 시작된다는 것이다. 달력의 정확한 월을 알고자한다면 다음과 같이 해야 한다.

예) get(Calendar.MONTH)+1

 

● SUNDAY(=1), MONDAY(=2), TUESDAY, WEDNESDAY

 ,THURSDAY, FRIDAY, SATURDAY(=7)

 : 각각의 요일을 나타낸다.

 

● DAY_OF_WEEK : 요일을 얻거나 바꾸자할 때 사용한다.

 

● DAY_OF_MONTH : 일자를 나타낸다.(DATE와 동일)

 

● AM_PM : 오전/오후

 

 

■ 예제

 

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
32
33
public static void main(String[] args) {
    Calendar cc = Calendar.getInstance();
 
    // 2013년 2월 26일 설정
    cc.set(2013, 1, 19); // 월은 0~11이므로
    System.out.println("날짜 : " + print(cc));
 
    int w;
    // 주(week)의 시작날짜 구하기
    Calendar sday = (Calendar) cc.clone();
 
    // cc객체를 복사하여 새로운 객체 생성
    w = cc.get(Calendar.DAY_OF_WEEK) - 1;
    sday.add(Calendar.DAY_OF_MONTH, w * (-1));
    System.out.println("주 시작날짜 : " + print(sday));
 
    // 주(week)의 마지막날짜 구하기
    Calendar eday = (Calendar) cc.clone();
    w = 7 - cc.get(Calendar.DAY_OF_WEEK);
    eday.add(Calendar.DAY_OF_MONTH, w);
 
    System.out.println("주 마지막 날짜 : " + print(eday));
 
}
 
public static String print(Calendar cal) {
    String[] week = { "일", "월", "화", "수", "목", "금", "토" };
 
    String str = String.format("%d %d %d %s요일", cal.get(Calendar.YEAR),
            cal.get(Calendar.MONDAY) + 1, cal.get(Calendar.DATE),
            week[cal.get(Calendar.DAY_OF_WEEK) - 1]);
    return str;
}

 

'java' 카테고리의 다른 글

날짜관련  (0) 2013.07.25
Date, SimpleDateFormat  (0) 2013.07.25
byte[] ↔ String  (0) 2013.07.25
byte  (0) 2013.07.25
AWT 예제  (0) 2013.07.25
Posted by 1+1은?
2013. 7. 25. 16:52
1
2
3
4
5
6
7
8
9
10
11
12
public static void main(String[] args) {
    String s = "대한민국";
 
    byte[] b = s.getBytes(); // 문자열을 바이트배열에 할당
 
    for (byte bb : b) {
        System.out.println(bb);
    }
 
    String ss = new String(b); // 바이트배열을 다시 문자열로..
    System.out.println(ss);
}


'java' 카테고리의 다른 글

Date, SimpleDateFormat  (0) 2013.07.25
Calendar, GregorianCalendar  (0) 2013.07.25
byte  (0) 2013.07.25
AWT 예제  (0) 2013.07.25
String  (0) 2013.07.25
Posted by 1+1은?