본문 바로가기

IT Data/#Java

[Java] Properties, Timer, XML, Buffer

[Properties]

public class Test1 {

* 특징 : hashmap과 구조가 비슷하다. 키, 밸류 값을 사용하는 것도 같으며 키셋을 통해 값을 찾는 것도 비슷하다.

           단 다른 점이 있다면 프로그램의 환경 설정 파일 저장등에 사용될 수 있다는 점이다.

public static void main(String[] args) {

Properties prop = new Properties();

prop.setProperty("서울","1000"); -> 프로퍼티객체.SetPropertykeyvalue) 으로 프로퍼티에 저장이 가능하다.

prop.setProperty("부산","300");

prop.setProperty("대구","200");

prop.setProperty("광주","150");

Iterator<Object> it = prop.keySet().iterator();-> 프로퍼티는 오브젝트형만 저장 가능하기 때문에 Iterator(반복자)

                                                                                  사용시에는 Obeject형으로 값을 받아 저장할 수 있게 해야한다.

while (it.hasNext()) {

String key = (String)it.next();->오브젝트형의 데이터만을 가지고 있기 때문에 다른 형태로의 

                                                                  다운캐스팅이 필요하다. 해당 프로퍼티는 String 형태의 Key값을 가졌으므로

                                                                   (String)을 이용해 다운캐스팅한다.

String value = (String)prop.getProperty(key); -> Value값도 역시 Object형이므로 다운캐스팅을 해준다.

System.out.println(key + " : " + value);

}

-  프로퍼티의 내용 삭제

//prop.remove(key); -> 해당키값을 찾아 key, value를 제거

- 파일로 저장

String pathname = "test.properties";->파일의 확장자명이 properties임.

try {


FileOutputStream fos = new FileOutputStream(pathname); -> 파일로 저장하기 위해선 FileOutputStream을

                                                                                                              선언해 줄 필요가 있다.

* 파일에 저장 ("키 =값" 의 형태로 저장. 한글은 유니코드로 저장.)

prop.store(fos, "도시별인구"); -> 프로퍼티객체.store출력스트림객체코멘트 )

     

    \uB300\uAD6C=200   -> 대구 = 200 

    \uC11C\uC6B8=1000  -> 서울 = 1000

     :                :           등으로 저장되어있다.

fos.close();

} catch (Exception e) {

// TODO: handle exception

}

* properties 파일 불러오기 (키=값 형태로 저장되어있어야 함)

try {

FileInputStream fis = new FileInputStream(pathname); -> 불러오기 위해선 FileInputStream을 선언해야한다.

Properties pp = new Properties();

pp.load(fis);-> 프로퍼티객체.load(입력스트림객체)

fis.close();

- 출력

pp.list(System.out); -> 프로퍼티객체.list(출력스트림)을 통해 프로퍼티의 리스트를 전부 출력하여준다.

System.out.println(pp.getProperty("서울"));

System.out.println(pp.get("부산"));

} catch (Exception e) {

// TODO: handle exception

}

* XML형식으로 저장

try {

FileOutputStream fos = new FileOutputStream(pathname);

prop.storeToXML(fos, "도시이름"); ->프로퍼티객체.storeToXML출력스트림객체코멘트 )로 XML저장가능

fos.close();

} catch (Exception e) {

// TODO: handle exception

}

* XML형식 불러오기

try {

FileInputStream fis = new FileInputStream(pathname);

Properties pp = new Properties();

pp.loadFromXML(fis);->프로퍼티객체.loadFromXML(입력스트림객체)로 XML저장가능

fis.close();

pp.list(System.out);

} catch (Exception e) {

// TODO: handle exception

}

}

}

[Timer]
* 특징 : 스레드의 일종으로서 TimerTask를 통해 해야할 일을 지정하고 일정시간에 따라 행동하도록 한다.
public class Test2 {
public static void main(String[] args) {
new TimerTest();
}
}
class TimerTest{
public TimerTest() {
* TimerTask : Timer에 의해 한번 또는 여러번 반복 실행 되도록하는 스케줄링
TimerTask task = new TimerTask() { -> 이클립스에서 익명클래스를 바로지정해준다.
@Override//반드시 오버라이드 해야하는 메소드.
public void run() {
printDays();
}
}; -> 익명클래스의 선언엔 반드시 ; 을 잊지않도록 한다.
Timer t = new Timer();
//t.schedule(task, 1000);-> 1초후에 한번 실행
//t.schedule(task, 2000, 1000);-> 2초쉬고 1초후에 한번 실행
//t.schedule(task, new Date(System.currentTimeMillis()), 1000);-> 바로시작
- 타이머취소
//t.cancel();
* 다음날 0분0시0초에 실행해서 하루에 한번씩 실행
Calendar cal = Calendar.getInstance(); -> calendar객체를 선언하면 현재의 시간이 들어온다.
cal.add(Calendar.DATE, 1);-> 현재시간으로부터 1일을 더 더함
- set을 통해 ms(miliSeconds)까지 0으로 세팅
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
t.schedule(taskcal.getTime()24*60*60*1000);-> 타이머객체.schedule(타이머태스크객체실행할시각반복할시          
                                                                                                                                               간의길이(Long형태))
                                                                                 해당 task를 다음날 0분0시0초에 86400초(하루)에 한번 실행한다.
}
private void printDays(){
Calendar date = Calendar.getInstance();
int y = date.get(Calendar.YEAR);
int m = date.get(Calendar.MONTH)+1;
int d = date.get(Calendar.DATE);
int h = date.get(Calendar.HOUR);
int mi = date.get(Calendar.MINUTE);
int s = date.get(Calendar.SECOND);
String str = String.format("%4d년%02d월%02d일 %02d:%02d:%02d", y, m, d, h, mi, s);
System.out.println(str);
}
}
[systemProperties]
* 시스템 정보확인
public class Test4 {
public static void main(String[] args) {
- Properties prop = System.getProperties(); -> 현재 시스템의 정보를 가져온다.
Iterator<Object> it = prop.keySet().iterator(); -> Property는 key와 value의 형태를 가지며 Object형만을 가지므로
                                                                                   Iterator는 반드시 Object형이어야한다.
while (it.hasNext()) {
String key = (String) it.next();
String value = (String)prop.getProperty(key);
System.out.println(key + " --> " + value);
}
}

}
[Buffer]
public class Test6 {
public static void print(ByteBuffer buffer){
ByteBuffer newBuffer = buffer.duplicate();-> buffer의 값을 newBuffer에 복사한다는 의미
System.out.println("포지션 : " + newBuffer.position());->데이터를 읽어올 위치
System.out.println("리미트  : " + newBuffer.limit());-> 버퍼의 길이
System.out.println("크기 : " + newBuffer.capacity());-> 버퍼의 실제크기
byte b;
newBuffer.position(0); -> 버퍼객체의 데이터를 읽을 위치를 처음으로 맞춘다.
newBuffer.limit(newBuffer.capacity()); -> 데이터를 담을 길이를 설정한다.
for (int i = 0; i < newBuffer.capacity(); i++) {
b = newBuffer.get(); -> get()메소드를 이용해 Byte배열 b의 내용을 하나씩 가져오면서 다음 위치로 이동한다.
System.out.print(b + " : 0x" + Integer.toHexString(b&0xff) + ", ");
}
System.out.println();
System.out.println("===============================");
System.out.println("포지션 : " + newBuffer.position());
System.out.println("리미트  : " + newBuffer.limit());
System.out.println("크기 : " + newBuffer.capacity());
public static void main(String[] args) {
* 버퍼의 크기 지정
ByteBuffer buffer = ByteBuffer.allocate(12); -> allocate(크기)를 통해 입력받을 버퍼의 크기를 정할 수 있다.
print(buffer);
* 버퍼에 값 저장
buffer.put((byte)65);-> 버퍼객체.put(바이트형태의값); 으로 버퍼에 값을 저장한다. 저장하는 값은 꼭 바이트형으로.
buffer.put((byte)66);
buffer.put((byte)67);
print(buffer); -> 65, 66, 67 출력
* byte배열의 내용복사
buffer.put(new byte[]{(byte)97, (byte)98,(byte)99})-> 버퍼에 배열의 내용이 순서대로 들어간다.
print(buffer);-> 65, 66, 6797, 97, 99 출력
System.out.println("현재위치" + buffer.position());
System.out.println("현재위치내용 : " + buffer.get());
buffer.position(2);
System.out.println("내용 : " + buffer.get());//현재위치를 출력하고 다음으로 넘어감. position3
System.out.println("내용 : " + buffer.get());// position4
System.out.println("현재위치" + buffer.position());//4가됨.
buffer.position(0);
byte bb[] = new byte[3];
buffer.get(bb);-> get()의 ()안에 byte배열을 넣는 경우 해당위치의 버퍼에서부터 배열의 크기만큼 
                                         갯수를 맞추어 돌려준다. (위치가 0이고 배열크기가 3이면 위치 0에서부터 3개까지) 
System.out.println("현재위치" + buffer.position());//
for (int i = 0; i < bb.length; i++) {
System.out.println(bb[i]);
}
buffer.flip();-> 리미트를 capacity로 설정하고 position은 0으로 설정한다.
System.out.println("flip후 위치 : " + buffer.position());
}
}
[Channel]
public class Test7 {
public static void main(String[] args) throws Exception {
String str = "다음주부터는 JSP/Servelet를 수업합니다.";
* 버퍼를 이용한 파일저장
FileOutputStream fos = new FileOutputStream("test.txt");
- 바이트버퍼에 문자열을 담는다.
byte[] b = str.getBytes(); -> 문자열.getBytes()는 문자열의 바이트를 받아온다.
ByteBuffer buffer ByteBuffer.wrap(b);-> b의 길이만큼 바이트버퍼 배열을 생성한 후 배열의 내용을 
                                                                          바이트 버퍼에 복사.
*  바이트 버퍼의 내용을 파일에 저장.
- 입출력 스트림으로는 바로 버퍼를 쓸 수 없다.
* Channel : 연결통로의 의미로서 바이트버퍼는 Channel을 거쳐 입출력스트림에 들어갈 수 있게된다.
                               ||                    ||     입출력스트림
                               ||      channel   ||          ↓
               ByteBuffer=======================>  
                               ||                    ||          ↓
                               ||                    ||          ↓
FileChannel channel = fos.getChannel(); -> 해당 출력 스트림에서 채널객체를 얻어온다.
channel.write(buffer); -> 채널객체를 통해 바이트버퍼의 내용을 파일에 쓸 수 있다.
channel.close();
//=================================================================================
FileInputStream fis = new FileInputStream("test.txt");
FileChannel channel1 = fis.getChannel(); ->  해당 입력 스트림에서 채널객체를 얻어온다.
ByteBuffer bbb = ByteBuffer.allocate((int)channel1.size()); -> 채널객체의 size는 바이트형태이며 alloacate의
                                                                                                       ()안에 들어갈 형태는 int형이기 때문에 형변환
                                                                                                       을하여 버퍼의사이즈를 정해주어야 한다.
channel1.read(bbb); -> 바이트버퍼에 채널을 통해 읽어온 내용을 저장한다.
bbb.flip(); -> 바이트버퍼의 처음읽을위치를 0으로 길이를 최대크기만큼 지정한다.
byte []b1 = new byte[bbb.limit()]; -> 버퍼의 최대길이만큼 바이트배열을 지정한다.
bbb.get(b1); -> 버퍼의 내용을 바이트배열에 저장한다.
String str1 = new String(b1); -> 새로운 String객체의 선언시 바이트배열을을 ()속에 넣으면 바이트배열을
                                                            문자로 바꾸어 String객체에 넣게 된다.
System.out.println(str1);
channel1.close();
}
}