'프로그래밍/JAVA프로그래밍'에 해당되는 글 42건

  1. 2012.07.29 File I/O filter처리
  2. 2012.07.29 File I/O
  3. 2012.07.29 예외처리(Exception), try catch finally
  4. 2012.07.29 난수구하기 및 수학함수
  5. 2012.07.29 java 시간 날짜 처리
  6. 2012.07.29 String class, String buffer
  7. 2012.07.29 boxing, unboxing, wrapperClass
  8. 2012.07.29 object클래스
  9. 2012.07.29 제너릭
  10. 2012.07.28 collection값 빼오기

* byte계열
  DataInputStream   -|
                     |-Primitive Data를 입출력하는 기능제공.
  DataOutputStream  -|

int i = 1456729;

FileOutputStream fo;
fo.write(i);

* project : day27
  package : file.io.filter
  class : DataStreamTest

package file.io.filter;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class DataStreamTest {
 private static String fileName = "d:\\prim.dat";
 public static void writeData(){
  DataOutputStream dos = null;
  try {
   dos = new DataOutputStream(new FileOutputStream(fileName));
   dos.writeInt(301201001);
   dos.writeBoolean(false);
   dos.writeLong(200100101010100L);
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }finally{
   if(dos!=null){
     try {
     dos.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }
 public static void readData(){
  DataInputStream dis = DataInputStream();
  try {
   dis = new DataInputStream(new FileInputStream(fileName));
   int i = dis.readInt();
   boolean b = dis.readBoolean();
   long l = dis.readLong();
   System.out.println(i);
   System.out.println(b);
   System.out.println(l);
//   System.out.println(i+b+l);
   System.out.println(i+"\n"+b+"\n"+l);
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }finally{
   if(dis!=null){
    try {
     dis.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
  
 }
 private static DataInputStream DataInputStream() {
  // TODO Auto-generated method stub
  return null;
 }
 public static void main(String[] args) {
  writeData();//binary로 생겨서 editor로 안읽힌다.
  readData();//파일로부터 저장되어있는 값을 읽어 들인다.
 }
 
}

--------------------
==========================================================================

* 예제
Human h = new Human("홍길동",20,'B',170.9,new AddressDTO("111-222","서울특별시 송파구");
DataOutStream dos = new DataOuputStream(new FileOutputStream("human.dat");
dos.writeUTF(h.getName());
dos.writeInt(h.getAge());
dos.writeUTF(h.getAddress().getZipCode());

* ObjectInputStream   -           입력 -> 객체 역직렬화
                       |- 객체를  입출력 하기위한 기능을 제공
  ObjectOutputStream  -           출력 -> 객체 직렬화


- java.io - Serializable를 implements한 class의 객체들만 직렬화 할 수 있다. (크게 공통점이 없는 것들을 하나의 것으로 만들어 주는 것이 인터페이스다. 뒤에 able이 붙는다.)
                 

       직렬화
name = "홍길동"   --------------------> 홍길동 10 b 180
age = 10;         <--------------------
bloodType = 'b'      역직렬화
tall = 180

package : day27

 

* project : day27
  package : file.io.filter
  class : ObjectStreamTest
   PersonDTO


package file.io.filter;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class ObjectStreamTest {
 private static String fileName = "d:\\person.obj";
 public static void wrtiteObject(Object obj){
  //인수로 받은 객체를 person.obj에 출력
  //ObjectOutputStream 이용. 객체를 출력 - 객체 직렬화,
  //                                            출력대상 :  instance변수의 값(attribute)
  ObjectOutputStream oos = null;
  try {
   //연결 + 필터
   oos = new ObjectOutputStream(new FileOutputStream(fileName));
   //쓰기 - writeObject(object)
   oos.writeObject(obj);
   
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }finally{
   if (oos != null) {
    try {
     oos.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }
 public static Object readObject(){
  //Person.obj파일에 저장된 객체 정보를 읽어 들여 다시 객체로 만든다.
  //ObjectInputStream - 객체를 입력받는 메소드 : 객체 역직렬화
  //메소드 : readObject() ; Object
  ObjectInputStream ois = null;
  Object obj = null;
  //연결 + 필터
  try {
   ois = new ObjectInputStream(new FileInputStream(fileName));
   //읽기
   obj = ois.readObject();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  }finally{
   if (ois != null) {
    try {
     ois.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
  return obj;
 }
 public static void main(String[] args) {
  AddressDTO address = new AddressDTO("111-222","서울시 송파구 가락동");
  PersonDTO p = new PersonDTO("id-111","1111","홍길동",20,address);
  wrtiteObject(p);
  Object obj = readObject();
  PersonDTO pto = (PersonDTO) obj;
  System.out.println(pto);
 }
}

-------------------
package file.io.filter;

import java.io.Serializable;

public class PersonDTO implements Serializable{
 private String id;
 private String password;
 private String name;
 private int age;
 private AddressDTO address;
 //생성자, setter/getter, toString
 public PersonDTO() {
 }
 public PersonDTO(String id, String password, String name, int age) {
  this.id = id;
  this.password = password;
  this.name = name;
  this.age = age;
 }

 public PersonDTO(String id, String password, String name, int age,
   AddressDTO address) {
  this.id = id;
  this.password = password;
  this.name = name;
  this.age = age;
  this.address = address;
 }
 public AddressDTO getAddress() {
  return address;
 }
 public void setAddress(AddressDTO address) {
  this.address = address;
 }
 public String getId() {
  return id;
 }
 public void setId(String id) {
  this.id = id;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 @Override
 public String toString() {
  return "PersonDTO [id=" + id + ", password=" + password + ", name="
    + name + ", age=" + age + ", address=" + address + "]";
 }
 
}

-----------------------
package file.io.filter;

import java.io.Serializable;

public class AddressDTO implements Serializable{
 private String zipcode;
 private String address;
 //생성자, setter/getter, toString
 public AddressDTO(String zipcode, String address) {
  this.zipcode = zipcode;
  this.address = address;
 }
 public String getZipcode() {
  return zipcode;
 }
 public void setZipcode(String zipcode) {
  this.zipcode = zipcode;
 }
 public String getAddress() {
  return address;
 }
 public void setAddress(String address) {
  this.address = address;
 }
 @Override
 public String toString() {
  return "AddressDTO [zipcode=" + zipcode + ", address=" + address + "]";
 }
 
}

//결과 : PersonDTO [id=id-111, password=1111, name=홍길동, age=20, address=AddressDTO [zipcode=111-222, address=서울시 송파구 가락동]]

'프로그래밍 > JAVA프로그래밍' 카테고리의 다른 글

File I/O  (0) 2012.07.29
예외처리(Exception), try catch finally  (0) 2012.07.29
난수구하기 및 수학함수  (0) 2012.07.29
java 시간 날짜 처리  (0) 2012.07.29
String class, String buffer  (0) 2012.07.29
Posted by 조은성
,

* I/O (Input/Output) - 연결하고 읽고 쓰고, 끊는다.

- 표준입출력 : 키보드로 입력받고 모니터로 출력
- 파일입출력 : 파일의 것을 읽거나 파일로 출력
- network : 네트워크로 연결되어 있는 다른 컴퓨터와 교환
- 객체 직렬화 : 기본 데이터 (프리미티브 타입+문자열)
                객체 데이터       : 읽고 쓰는 대상이 객체 일때
데이터를 저장 :  배열, ArrayList, Map, 파일, DB(select, update, delete, insert, trigger, tranjection, join)

- Stream : 데이터의 흐름(ex : 물이 흘러가는 통로)
- input : 데이터를 읽어 들이는 통
- output : 데이터를 흘려 보내는 통
* 항상 읽고 쓰는 것의 기준은 프로그램이다.


* java.io  (성격에 따라서 세가지 구분법이 있다.)
1. Input/Output 계열로 구분
2. Node/Filter  계열로 구분

3. byte/char    계열로 구분

- Node : 연결이 목적인 Stream class
연결이 목적이 있는 입출력을 위한 기능만 제공
- Filter계열 : 기존의 stream(연결)에 읽고 쓰는 기능을 추가하는 class
기능 주기가 목적이므로 연결기능은 없다.
->Node로 연결하고 Filter로 기능추가.


* I/O

try{
 1. 연결 - Node
 기능추가 - Filter
 2.I/O
}finally{
 3.연결끊기 - Filter
}

--------------------------


- byte 계열 : 1byte단위 입출력처리 하는 Stream
  binart code 입출력시 사용.
- charater 계열 :  2byte 단위 입출력 처리 Stream class
  text 입출력시 사용

 

*I/O정리
--------------------------------------------------------------------------------------------
            |           Input계열                  |  Output계열
--------------------------------------------------------------------------------------------
            | byte계열          | character계열    |  byte계열          |  character계열
--------------------------------------------------------------------------------------------
최상위class | InputStream       | Reader           | OutputStream       |  Writer
(추상)      |                   |                  |                    |              
--------------------------------------------------------------------------------------------
Node계열    | FileInputStream   | FileReader       | FileOuputStream    |  FileWriter
--------------------------------------------------------------------------------------------
Filter계열  | ObjectInputStream | BufferedReader   | ObjectOutputStream | BufferedWriter 
            |  DataInputStream  | InputStreamReder | DataOutputStream   | OuputStreamWriter
            |                   |                  |                    | PrintWriter
--------------------------------------------------------------------------------------------

* Text를 I/o할때는 BufferedReader로 읽어 들이고 PrintWriter로 써준다.

* Node 계열의 생성자의 인수 : 연결대상.
  Filter계열 생성자의 인수 :  Stream class type
                              Reader/Writer
                              InputStream/OutputStream

InputStream                      
- 1byte - read() : int ->char(1byte)
- EOF : -1

byte b[] = new byte[100];
read(byte[]) : int //int는 읽은 byte의 수를 리턴해준다. EOF를 만나면 -1을 리턴해준다.

 

Reader
- read() : int ->char(2byte)
EOF : -1

char b[] = new char[100];
read(char[]) : int //int는 읽은 글자의 수를 리턴해준다. EOF를 만나면 -1을 리턴해준다.

 

ex :

int i =in.read();
while(i!=-1){
 i=in.read();
}

//파일에 내용이 있을때까지 내용을 읽어 들어라.

* byte나 char 만 읽어 오므로 부호비트가 무조건 0이어서 -가 나올 수 없다. 그래서 EOF는 -1을 쓴다.

* close();연결끝는 메소드 , 이 메소드는 finally에 들어간다. (예외처리중)

* in.read()는 읽을게 없으면 읽을게 생길때 까지 기다린다.(멈춰있다가 읽을게 생기면 읽는다.) //I/O blocking.

* 출력
1. OutputStream
write(int) : void
인수로 받은 byte를 출력

* write(byte[]) //byte배열내의 data들을 한번에 출력, 만약 byte[10]이라면 10개의 글자를 읽어와서 한번에 출력한다.
  write(byte[], int startIndex, int length) //byte배열내의 data중 startIndex에서 length만큼의 data출력.

 
2. Writer
write(int) : void
인수로 받은 char를 출력

* EOF는 -1을 읽어서 -1을 리턴하는 것이 아니라 EOF 파일의 끝을 만나면 -1을 리턴해주는 것이다.
  write(char[])
  write(char[], int idx, int length)
  write(String)
 
*  OutputStream 와 Writer의 공통 메소드
- close(); : 연결끊기
- flush() : 버퍼를 이용하는 stream의 버퍼내 Data들을 강제출력 처리.(ex : 화장실물내리기,)//close()전에 사용해서 버퍼에 있는 것을 다 출력시킨 후에 연결을 끊어주는 경우가 많다.

* 입출력 코딩 pattern
try{
1. 연결 - Node계열의 stream으로 연결한다.
   Filter추가 - Filter계열의 Stream을 추가해 준다.
2. I/O 작업 read() - Filter로 읽고 쓴다.
            write()
}finally{
3. 연결끊기 close() - Filter를 끊으면 Node도 같이 끊어진다.
}

       Filter
*       |              Node로 연결
        |             |
    ㅡㅡ|ㅡㅡㅡㅡㅡㅡ |ㅡㅡ
p/g ----|------------------  File
    ----|------------------
    ㅡㅡ|ㅡㅡㅡㅡㅡㅡㅡㅡㅡ
        |        |
               Filter

* Node로 통로를 만들고 Filter로 통로를 확장시키고 다 사용했다 하면 Filter로 연결을 끊어 주면 Node와 Filter다 연결이 끊어진다.
* File IO - 파일과 연결해서 I/O.

FileInputStream/ FileOutputStream
(binary code를 읽음.ex: 그림)
FileReader    /  FileWriter
(byte)           (char)

(String file명)

ex :

FileWriter fw = new FileWriter("a.txt");
                                  ^
                                  |
                                상대 경로 : 나를 기준으로(<-를 실행하고 있는 class파일을 기준으로 찾아 들어간다.) ..->부모 디렉토리, .->현재 디렉토리(폴더)
                                절대 경로 : C://a.txt 파일이 있는 전체주소를 다 써준다.

* 파일을 찾을 수 없으면 FileNotFoundException을 낸다.

-------------------------------------------------------------------------

*
project : day26
package : file.io
class : FileStreamTest
 
D:\Penguins.jpg


package file.io;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileStreamTest {
 public static void main(String[] args) {
  FileInputStream fi = null;
  FileOutputStream fo = null;
  try {
   //1.연결
   fi = new FileInputStream("d:\\Penguins.jpg");//파일이 있다면 그림파일과 연결이 끝난 상태가 된다.
   //fo = new FileOutputStream("d:\\Penguins2.jpg"); //기존 데이터 붙여쓰기
   fo = new  FileOutputStream("d:\\Penguins.jpg",true); //파일 이어 붙이기
   //2. I/O 작업(읽는 작업, 쓰는 작업)
   int data = fi.read(); //1 바이트를 읽어옴
   int count = 0;
   
   long l1 = System.currentTimeMillis();
   while(data!=-1){
    fo.write(data);//출력
    data = fi.read();//입력
    count++;
   }
   long l2 = System.currentTimeMillis();
   
   System.out.println("읽은 횟수 : "+count);
   System.out.println("처리 시간 : "+(l2-l1)+"밀리초");
   System.out.println("처리 시간 : "+(l2-l1)/1000+"초");
  //3.정상적으로 끝났을 시에만 연결끊기
  //fi.close(); 
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally{
   //3. 연결끊기
   if(fi!=null){//끝는 객체가 null이 아닌 경우에만 연결을 끊어라.(연결이 되어있는 경우만)
   try {
    fi.close();
   } catch (IOException e) {
   
    e.printStackTrace();
   } 
   }
   if(fo!=null){
    try {
     fo.close();
    } catch (IOException e) {
    
     e.printStackTrace();
    }
   }
  }
 }
}

--------------------
===============================================================


*
project : day26
package : file.io
class : FileArrayStreamTest
 
package file.io;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileStreamArrayTest {
 public static void main(String[] args) {
  FileInputStream fi = null;
  FileOutputStream fo = null;
  try {
   //1.연결
   fi = new FileInputStream("d:\\Penguins.jpg");//파일이 있다면 그림파일과 연결이 끝난 상태가 된다.
   fo = new FileOutputStream("d:\\Penguins2.jpg"); //기존 데이터 붙여쓰기
   //fo = new  FileOutputStream("d:\\Penguins2.jpg",true); //파일 이어 붙이기
   //2. I/O 작업(읽는 작업, 쓰는 작업)
     long l1 = System.currentTimeMillis();
     int count = 0;
     byte[] buff = new byte[10000];
     int length = fi.read(buff);
     while(length !=-1){
      fo.write(buff);
      length = fi.read(buff);
      count++;
     }
     long l2 = System.currentTimeMillis();
     System.out.println("반복횟 수 : "+count);
     System.out.println("걸린 시간 : "+(l2-l1)+"밀리초");
     System.out.println("걸린 시간 : "+(l2-l1)/1000+"초");   
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
  
   e.printStackTrace();
  }finally{
   //3. 연결끊기
   if(fi!=null){//끝는 객체가 null이 아닌 경우에만 연결을 끊어라.(연결이 되어있는 경우만)
   try {
    fi.close();
   } catch (IOException e) {
   
    e.printStackTrace();
   } 
   }
   if(fo!=null){
    try {
     fo.close();
    } catch (IOException e) {
    
     e.printStackTrace();
    }
   }
  }
 }
}

-----------------------------
============================================================

file - 17byte
byte[] b = new byte[5];
int i = fi.read(b);
while(i!=-1){
 fo.write(b);
 i = fi.read(b);
}

배열의 크기가 5므로 2byte까지 넣고 3byte가 남아서 파일의 크기가 커진다.

그래서 파일의 크기를 같게 해주려면

file - 17byte
byte[] b = new byte[5];
int i = fi.read(b);
while(i!=-1){
 fo.write(b,0,i);
 i = fi.read(b);
}

를 해줘야한다.

위에 꺼 수정 예제

package file.io;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileStreamArrayTest {
 public static void main(String[] args) {
  FileInputStream fi = null;
  FileOutputStream fo = null;
  try {
   //1.연결
   fi = new FileInputStream("d:\\Penguins.jpg");//파일이 있다면 그림파일과 연결이 끝난 상태가 된다.
   fo = new FileOutputStream("d:\\Penguins2.jpg"); //기존 데이터 붙여쓰기
   //fo = new  FileOutputStream("d:\\Penguins2.jpg",true); //파일 이어 붙이기
   //2. I/O 작업(읽는 작업, 쓰는 작업)
     long l1 = System.currentTimeMillis();
     int count = 0;
     byte[] buff = new byte[10000];
     int length = fi.read(buff);
     while(length !=-1){
      fo.write(buff,0,length);
      length = fi.read(buff);
      count++;
     }
     long l2 = System.currentTimeMillis();
     System.out.println("반복횟 수 : "+count);
     System.out.println("걸린 시간 : "+(l2-l1)+"밀리초");
     System.out.println("걸린 시간 : "+(l2-l1)/1000+"초");   
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
  
   e.printStackTrace();
  }finally{
   //3. 연결끊기
   if(fi!=null){//끝는 객체가 null이 아닌 경우에만 연결을 끊어라.(연결이 되어있는 경우만)
   try {
    fi.close();
   } catch (IOException e) {
   
    e.printStackTrace();
   } 
   }
   if(fo!=null){
    try {
     fo.close();
    } catch (IOException e) {
    
     e.printStackTrace();
    }
   }
  }
 }
}

*


--------------------------
====================================================================

*
project : day26
package : file.io.character
class : FileReaderWriterTest


package file.io.character;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileReaderWriterTest {
 public static void main(String[] args) {
  FileReader fr = null;
  FileWriter fw = null;
  //d:\news.txt 읽어서 d:\news2.txt로 쓰기 - char[]
  
  try {
   fr = new FileReader("d:\\news.txt");
   fw = new FileWriter("d:\\news2.txt"); //연결할때마다 다 지우고 새로쓴다.
   //fw = new FileWriter("d:\\news2.txt",true); //연결할때 이어쓴다.
   
   char[] buff = new char[10000];
   int count = 0;
   int length = fr.read(buff);
   while(length!=-1){
    fw.write(buff,0,length); //읽은 글자 수만큼만 써라.
    length = fr.read(buff);
    count++;
   }
   System.out.println("반복횟수 : "+count);
  } catch (FileNotFoundException e) {

   e.printStackTrace();
  } catch (IOException e) {

   e.printStackTrace();
  }finally{
   if(fr!=null){ //파일연결이 실패하면 null이 들어간다. 그래서 null이 아닐시만 연결을 끊어줘야한다.
   try {
    fr.close();
   } catch (IOException e) {

    e.printStackTrace();
   }
   }
   if(fw!=null){
    try {
     fw.close();
    } catch (IOException e) {

     e.printStackTrace();
    }
   }
  }
  
 }
}

-----------------------------------
========================================================================

* 2012-3-29

- Input/Output

- Node계열(연결) / Filter계열(기능추가)

- byte계열(1byte) / character(2byte) - 언제쓰는지 질문
* a.txt
FileReader
FileWriter

* BufferedReader : Enter를 기준으로 읽어 들이는 기능.(라인단위로 받아옴)


*     char(txt)    byte(binary)
----------------------------------
I :   Reader       InputStream
O :   Writer       OutputStream

 

Node : 연결대상
Filter : InputStream

* 사용
try{
1. 연결 - Node
   Filter추가
2. 읽고쓰기
}finally{
3. close();
}


-----------------------------------------------------------------------------
==============================================================================

 

*
project : day26
package : file.io.character.filter
class : BufferReaderWriterTest


package file.io.character.filter;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
 

public class BufferReaderWriterTest {
 public static void main(String[] args) {
  
 
 //Filter Stream을 이용한 입출력
 //BufferedReader와 PrintWriter를 이용해 news.txt->new3.txt로 입/출력
 FileReader fr = null;
 FileWriter fw = null;
 //Filter스트림
 BufferedReader br = null; //버퍼를 이용, 라인단위로 읽는 기능
 PrintWriter pw = null; //데이터 포멧에 맞게 출력, println(), print()기능
 try {
  //1-1연결
  fr = new FileReader("d:\\news.txt");
  fw = new FileWriter("d:\\news3.txt");
  //1-2 filter 스트림 추가
  br = new BufferedReader(fr);
  //pw = new PrintWriter(fw);
  pw = new PrintWriter(fw, true);//true : auto flush - println()하면 바로 출력된다. 버퍼를 이용하지 않고(쓸때마다 출력해야 하는 경우 사용한다.ex : 채팅프로그램)
  //2 read(BufferedReader)/writer(PrintWriter)
  String str = br.readLine();//엔터를 기준으로 읽어들임(엔터는 않읽는다.)//읽은것을 String으로 리턴
  while(str!=null){ //EOF : null을 리턴
   System.out.println(str);
   pw.println(str); //버퍼에 출력할것을 담아둔다.(버퍼의 크기가 꽉차면 그 버퍼만큼은 출력해준다.)
   str = br.readLine();
  }
 // pw.flush();//버퍼의 내용을 다 출력해준다.(버퍼에 있는 데이터를 최종 출력장소로 밀어내는 메소드
 } catch (FileNotFoundException e) {
  e.printStackTrace();
 } catch (IOException e) {
  e.printStackTrace();
 }finally{
  //3 연결 끊기
  if(br!=null){
  try {
   br.close(); //버퍼를 닫으면 연결이 끊어진다.
  } catch (IOException e) {
  
   e.printStackTrace();
  }
  }
  if(pw!=null){
    pw.close();
  }
 }

 }
}
//파일에 enter가 들어가면 파일의 크기가 약간 커질수도 있다.

'프로그래밍 > JAVA프로그래밍' 카테고리의 다른 글

File I/O filter처리  (0) 2012.07.29
예외처리(Exception), try catch finally  (0) 2012.07.29
난수구하기 및 수학함수  (0) 2012.07.29
java 시간 날짜 처리  (0) 2012.07.29
String class, String buffer  (0) 2012.07.29
Posted by 조은성
,

* 예외 : 프로그래머가 원하지 않는 방향으로 가는 것.
* 오류 : 프로그램이 정상적으로 실행하지 못하는 상황.
  1. Error : 심각한 오류(프로그램을 멈춰야 하는 오류) - H/W적 오류
  2. Exception : mild오류(심각하지 않음 오류) - s/w적오류(실행시 정상적인흐름(programmer가 의도한 흐름)으로 가지 못한 상황.

* Exception Handling(예외처리)
- 예외가 발생되었을때 프로그램이 정상적으로 처리되도록 해주는 것.

Throwable - 오류의 최상위
^       ^
|       |
Error   Exception
           ^
           |
     ---------------
     |             |
   Runtime        나머지
   (unchecked)    (checked)

 

 

 


- Exception - unchecked 계열(Handleing(처리) : compiler가 신경쓰지 않음), checked 계열(compiler가 체크)
- unchecked : 컴파일러가 Exceoption 처리여부를 체크 않함
  발생이유 : code상의 문제 때문에 발생 (100퍼센트 실행 시 오류가 남. 코드를 수정해 주는 것이 맞음)
             compiler의 check가 불가능한 경우.
             -> 처리(Handling)보다는 code 수정

- checked 계열 Exception : 컴파일러가 Exception 처리여부를 check
                         하지 않았을 경우 컴파일 에러 발생
  발생이유 :  code상 문제가 아니라 user가 잘못 사용하였거나 실행 환경상 문제로 발생
  - 발생 확률 :  50 : 50
  -> 처리가 필요.

* 오류가 나면 그자리에서 처리 하는게 아니라 오류가 나는 곳의 상위에서 처리한다.
* throw, throws, try, catch, finally
throw :  오류를 발생시키는 것
throws, try, catch, finally : 오류를 처리하는 것.(try, catch, finally는 셋이 같이 붙어 다닌다. )
* Exception class 정의하는 법.

* Exception class 작성(교재 P537)
  1. checked :  Exception을 extends
     unchecked : RuntimeException을 extends
  2. public class
  3. no-arg 생성자
     String 인수로 받는 생성자
  4. 필요한 Attribute, 메소드를 구현.
     이름 ; ~Exception

* project : day24
  package : exception.sample
  class : ExceptionTest
          Divide
          ZeroDivideException

 


package exception.sample;

public class ExceptionTest {
 public static void main(String[] args){
 Divide d = new Divide();
 int result = 0;
 try{
  result = d.divide(10,0);
 }catch(ZeroDivideException ze){
      System.out.println("오류가 발생했습니다.");
      try {
   result = d.divide(10, 5);
  } catch (ZeroDivideException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 System.out.println("나눈 결과 : "+result);
 }
}

---------

 

package exception.sample;

public class Divide {
 
 public int divide(int num1, int num2) throws ZeroDivideException{
   //num1을 num2로 나눈 값(몫)을 return
  if(num2==0){ //예외상황
   throw new ZeroDivideException();
   
  }
  return num1/num2;
 }
}


-----------

package exception.sample;
/*
 * Exception 클래스
 * 0으로 숫자를 나눴을 때의 예외상황을 표현하기 위한 클래스
 */
public class ZeroDivideException extends Exception{
 public ZeroDivideException(){}
 public ZeroDivideException(String message){
  super(message);
 }
}


------------
==========================================================
* Exception 발생(던진다) - throw (호출해준 사람한테 예외를 던져준다.)
  구문 :  throw Throwable의 객체;

num2 = 0;

* 예외처리 : throws - 예외발생할 메소드를 호출한 caller메소드에서 처리하도록 하는 것.
             try,catch,finally - 발생한 예외를 직접처리하는 것.

 
- 메서드 구문 :  [제한자] return type 이름([매개변수들]) throws [ExceptionType, . . .]{}
ex :  public void go() throws AEception, BException{}


                 
* 메소드 overriding - 하위 class에서 부모의 메소드 재정의
        (instance 메소드)
- 규칙 - 전제; 이름동일
  1. return type, 매개변수가 동일
  2. 하위의 접근제한자가 상위 것과 같거나 더 넓어야한다.
* 3. 부모가 throws 한것만 할 수 있다.( exception )
     -> 부모에서 throws 한것 안 할 수 있다.


* Exception

     ^
     |
  --------
  |       |
AException BException
  |      
------
|    |
A1Exception A2Exception


Super

public void go() throws AE{}

Sub
public void go(){} ok
public void go() throws AE,BE{} no
public void go() throws A1E,A2E extends Super(){}  ok

- try, catch, finally - 오류처리

try{
 오류(예외)발생 가능성이 있는 코드 ->throw
                                          ->메소드 호출 -> throws

}catch(예외(오류) type 변수선언){
 처리코드;
}

* ex :
try{
 1.AE
 2.BE
 3.CE
}catch(AE a){
 4.
}catch(BE b){
 5.
}catch(CE c){
 6.
}
 7.

2. BE발생

1.->2.X->5.->7. //이렇게 이동. 만약 위에 것에 오류가 나면 아래 있는 것이 실행할 의미가 없으면 이렇게 하고, 아랫것도 실행해야 되면 try{}catch(){}를 따로 잡아줘야 한다.


*

project : day24
package : exception.trycatch
class : ExceptionTest1


package exception.trycatch;

public class ExceptionTest1 {
 public static void main(String[] args) {
  /*
   * uncheck 계열의 Exception
   * ArrayIndexOutOfBoundsException - 배열의 index 범위를 넘었을때 발생
   * NullPointerException - null값을 가진 변수의 instance멤버 호출시 발생
   * ArithmethicException - 산술 연산상 문제 발생시 발생(0으로 나눈 경우)
   */
  String str = null;
  try{
  System.out.println(str.concat("def"));//100%이므로 수정하는게 맞지만 연습용으로 try{}catch(){}를 쓴다.
  }catch(NullPointerException ne){
   System.out.println("NullPointerException 발생");
   
  }try{
  System.out.println(10/0);
  }catch(ArithmeticException ae){
   System.out.println("ArithmeticException 발생");
  }
  int[] arr = {10,20,30};
  try{
  System.out.println(arr[10]);
  }catch(ArrayIndexOutOfBoundsException arre){
   System.out.println("ArrayIndexOutOfBoundsException 발생");
  }
  System.out.println("메인메소드 종료");
 }
}


---------
============================================================================
*
package exception.trycatch;

public class ExceptionTest2 {
 public static void main(String[] args) {
  String str = null;
  try{
  str.concat("def");
  int result = 10/0;
  int arr[]= {10,20,30};
  System.out.println(arr[0]);
  
  int i = Integer.parseInt("abcde");
  }catch(NullPointerException e){
   System.out.println("NullPointerException발생");
  }catch(ArithmeticException ae){
   System.out.println("ArithmeticException발생");
  }catch(ArrayIndexOutOfBoundsException ae){
   System.out.println("ArrayIndexOutOfBoundsException발생");
  }catch(Exception e){ //모든 Exception의 상위 개념으로 위에서 잡은 것 말고는 다 여기서 잡는다.
   System.out.println("Exception e");
  }
  System.out.println("메인메소드 종료");
 }
 
}
----------------------
==========================================================================

--------------------
=============================================================================


 
* 2012-3-27

 오류                                                
          |
----------------------
|                     |
에러                 예외
심각한H/w적           S/W적

 

 Throwable
            |
--------------------------
|                         |
Error                    Exception
                          |
                   --------------------------
                   |                         |
     unchecked : RunTimeException   checked : exception(checked 는 사용자가 메뉴얼 대로 사용하지 않거나 호출이 잘못되었을 시 사용하는 exception이다.)

* 오버라이딩 규칙에 걸려서 exception을 던지지 못할 경우에는 Runtime계열의 Exception을 만들어 던진다.
ex : ABCException a = new ABCException();
     WrapperException we = new WrapperException(a);
     throw new we;

* exception은 잘못된 상황이 나오면 잘못된 상황을 표현하기 위한 class(exception)를 만들면된다.
  
* RuntimeException도 컴파일시 구문에 적어주지 않아도 에러가 나지 않지만 구문만 보고도 사용자가 Exception이 난다는 것을 알아야 하기 때문에 구문에 throws를 사용해서 나타내준다.
ex :

public void b() throws NullPointerException{

 throw new NullPointerException();
}

* 상속구조의 Exception을 잡을 시에는 하위 것부터 잡아야 한다. 왜냐하면 상위를 먼저 잡으면 상위에서 예외를 다 처리하여 하위 예외는 왜 썼냐고 물으면서 에러를 내기 때문이다.
* catch안에 아무것도 구현안해도 예외처리를 한것이기는 하나 로그를 남겨야 한다. (오류를 남겨 두지 않으면 프로그램이 아무 이상 없는 것으로 보이는데 프로그램이 실행이 안되는 경우가 생길 수 있다.)

* Exception 발생
public void addProduct()throws SameIDException{
  throw new SameIDException();
}
  메소드 호출
try{
pm.addProduct();
}catch(SameIDException se){
}


* 개발에서는 catch에 printStackTrace();를 한다.

*
try{
 예외가 날 확률이 있는 코드
}catch(  e){
 예외처리
}finally{
무조건 실행
}

----------------------------

try{ 1->4->5
1       - AE발생
2
3
}catch(AE e){
4
}
5

-----------------------------


try{
1     
2
3
}catch(AE e){
4
}finally{
5
}

예외가 없으면 1->2->3->5
1번에서 예외가 나면 1->4->5
1번에서 catch에서 잡지 않는 에러가 나면 1->5


----------------------------------
*IO
try{

 1.연결
 2.교환

}catch(){

 예외처리

}finally{

 3.연결끊기

}

----------------------------------
try : 오류날 가능성이 있는 코드-->실행코드(정상)
catch : try 블럭에서 난 오류를 처리하는 코드
finally : try와 catch의 상황과 상관 없이 무조건 실행되야 하는 코드.->실행코드(정상)

* 가능
- try{}catch(){}finally{}
- try{}finally{}
- try{}catch{}

 

 

'프로그래밍 > JAVA프로그래밍' 카테고리의 다른 글

File I/O filter처리  (0) 2012.07.29
File I/O  (0) 2012.07.29
난수구하기 및 수학함수  (0) 2012.07.29
java 시간 날짜 처리  (0) 2012.07.29
String class, String buffer  (0) 2012.07.29
Posted by 조은성
,

* double d = Math.random(); //난수 발생 범위(0.0 <= x < 1.0)
* java.util.Random r = new Random();
Int i = r.nextInt();//인트의 범위까지 정수형을 리턴한다.
int i1 = r.nextInt(100);//0~(100-1)까지의 숫자를 랜덤적으로 리턴한다.

package random;

import java.util.Random;

public class RandomTest {

 public static void main(String[] args) {
  Random r = new Random();
  System.out.println(r.nextInt());//int 범위에있는 모든 수를 random하게
  System.out.println(r.nextBoolean());
  System.out.println(r.nextDouble());;
  System.out.println(r.nextLong());
  int i = r.nextInt();
  while(i>=0){
   i = r.nextInt();
  }
  System.out.println(i);
  i = r.nextInt(10);//0~9까지 리턴
  while(i!=10){
   i = r.nextInt(10);
  }
  System.out.println(i);
 }

}
--------------------------------
================================================================

* 2012-3-26
* Java.math.BigDecimal - double로 표현이 안되는 부동 소숫점 표현  -> 구문 :  new (BigDecimal("10.5");
            BigInteger - long으로 표현이 안되는 정수를 표현

* project : day23
  package : number
  class : BigDecimalTest


package number;

import java.math.BigDecimal;

public class BigDecimalTest {
 public static void main(String[] args) {
  System.out.println(2.00-1.11);
  BigDecimal d1 = new BigDecimal("2.0");
  BigDecimal d2 = new BigDecimal("1.10");
  // + : add(), - : substract(), / : divide(), * : multiply()
  BigDecimal result  = d1.subtract(d2);
  double d = result.doubleValue();
  System.out.println(result +" : "+ d);
  //1 : 나눌 수, 2 : scale - 소숫점 이하 몇자리 까지보여줄것인지, 3 : 소숫점 이하 처리방식
  result = d1.divide(d2,3,BigDecimal.ROUND_CEILING);//소수점 3자리까지 나타내라.
  System.out.println("나눈 결과 : "+result);
 }
}

'프로그래밍 > JAVA프로그래밍' 카테고리의 다른 글

File I/O  (0) 2012.07.29
예외처리(Exception), try catch finally  (0) 2012.07.29
java 시간 날짜 처리  (0) 2012.07.29
String class, String buffer  (0) 2012.07.29
boxing, unboxing, wrapperClass  (0) 2012.07.29
Posted by 조은성
,

* 시간, 날짜 처리
java.util.Date
java.util.Calendar

- GregorianCalendar

생성자 종류
GregorianCalendar()
GregorianCalendar(int y, m, d)
GregorianCalendar(int y, m, d, h, m)

.get(int year)

- 요일 (일요일(0)~토요일(6))

package calendar;

import java.util.*;
public class CalendarTest {
 public static void main(String[] args) {
  //현재 시간을 출력하는 프로그램을 만드세요.- Calendar, GregroianCalendar
  //Calendar c = Calendar.getInstance();    //아래 GregorianCalendar gc = new GregorianCalendar(); 이렇게 사용한 것과 같다.
//  GregorianCalendar gc = new GregorianCalendar();
//  TimeZone tz = TimeZone.getTimeZone("Europe/London");
//  gc.setTimeZone(tz);//영국시간대로 변경
  GregorianCalendar gc = new GregorianCalendar(2005,2, 20);

//  System.out.println(gc.isLeapYear(2012));  //윤년이 있는지 없는지를 알려줌.
  int year = gc.get(Calendar.YEAR);
  int month = gc.get(Calendar.MONTH)+1;
  int day = gc.get(Calendar.DATE);//Calendar.DAY_OF_MONTH
  String amPm = (gc.get(Calendar.AM_PM)==Calendar.AM) ? "오전":"오후";
  int hour = gc.get(Calendar.HOUR);//0~11, Calendar.HOUR_OF_DAY:0~23
  int minute = gc.get(Calendar.MINUTE);
  int second = gc.get(Calendar.SECOND);
  String dayOfWeek = null;
  switch(gc.get(Calendar.DAY_OF_WEEK)){
   case Calendar.SUNDAY:
    dayOfWeek = "일요일";
    break;
   case Calendar.MONDAY:
    dayOfWeek = "월요일";
    break;
   case Calendar.TUESDAY:
    dayOfWeek = "화요일";
    break;
   case Calendar.FRIDAY:
    dayOfWeek = "금요일";
    break;
   
  }
  //2011년 10월 4일 오전 11시 21분 23초 화요일
  System.out.println(year+"년 "+month+"월 "+day+"일 "+amPm+" "+hour+"시 "+minute+"분 "+second+"초 "+dayOfWeek);

 }
}


---------------
=======================================================

*세계시간 구하기(타임존 구하기)

package calendar;

import java.util.TimeZone;

public class PrintTimeZone {
 public static void main(String[] args) {
 String [] timeZone = TimeZone.getAvailableIDs();
  for(String tz : timeZone){
   System.out.println(tz);
  }
 }
}

----------
========================================================

* project : day23
package : calendar
class : CalendarTest2


package calendar;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;

public class CalendarTest2 {
 public static void main(String[] args) {
  long l1 = System.currentTimeMillis(); //현재시간을 1/1000 초로 알려줌. 1970.1.1.0.0.0.0초 부터
  for(int i =0;i<1000;i++){
//   System.out.println(i);
  }
  System.out.println(l1);
  long l2 = System.currentTimeMillis();
  System.err.println(l2 - l1);
  GregorianCalendar gc = new GregorianCalendar();
  long miliS = gc.getTimeInMillis();
  System.out.println(miliS);
  
  System.out.println("-----------SimpleDateFormat을 이용--------------");
  SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd a HH : mm : ss E"); //a는 오전,오후 E는 요일
  //String str = sf.format(gc); //GregorianCalendar와 SimpleDateFormat은 상속관계가 아니라 넣을 수 없다.
  
  Date d = gc.getTime();//GregorianCalendar을 Date 타입으로 바꿔준다.
  String str = sf.format(d); //GregorianCalendar와 SimpleDateFormat은 상속관계가 아니라 넣을 수 없다.
  System.out.println(str);
 }
 
}

'프로그래밍 > JAVA프로그래밍' 카테고리의 다른 글

예외처리(Exception), try catch finally  (0) 2012.07.29
난수구하기 및 수학함수  (0) 2012.07.29
String class, String buffer  (0) 2012.07.29
boxing, unboxing, wrapperClass  (0) 2012.07.29
object클래스  (0) 2012.07.29
Posted by 조은성
,

* 문자열 관리해주는 class - String, StringBuffer(String에 가기 전 임시저장소), StringBuilder
                            ->char[]로 처리한다. -> length : 글자수
                                                 -> idx : 글자의 위치

String s = "Hello";
     idx가  01234
만약에 s.charAt(4);//o 가 나온다.

char c1 = 'H';
char c2 = 'e';
char c3 = 'l';
char c4 = 'l';
char c5 = 'o';

char[] c = {'H','e','l','l','o'};

* String - 한번 객체가 만들어 지면 그 값은 절대 불변.
ex:
String s = "abc";//String s = new String("abc"); //한번 abc 문자열이 들어가면 죽을 때 까지 abc를 가지고 있는 객체가 된다.
s.concat("def"); //abc def가 따로 객체가 2개가 생긴다.
system.out.println(s); //결과 : abc

->값 : " "
  객체 : String s = "abc";
  String s = new String("abc");


* project : day23
  package : string
  class : StringTest

package string;

public class StringTest {
 public static void main(String[] args) {
  String s1 = "abcde";
  String s2 = new String("abcde");
  String s3 = "ABCDE";
  //글자수를 조회하는 메소드
  int strLength = s1.length();
  System.out.println(strLength);
  //두 String의 내용값이 같은지 비교
  System.out.println("s1 == s2 : "+(s1 == s2));//주소값 비교  다른객체를 비교하니 결과 :  false
  System.out.println("s1.equals(s2) : "+s1.equals(s2));//내용값 비교      //내용이 같으니 결과 : true
  System.out.println("s1.equals(s3) : "+s1.equals(s3));                     //대소문자가 달라서 결과 : false
  System.out.println("s1.equalsIgnoreCase(s3) : "+s1.equalsIgnoreCase(s3));//대소문자 무시하고 내용값 비교  //대소문자를 무시하니 결과 : true
  //조회하는 메소드들
  //특정문자열로 시작/끝나는지 비교
  //시작
  boolean flag = s1.startsWith("ab");//ab로 시작하는지?
  System.out.println("s1.startsWith(\"ab\") : "+flag);
  System.out.println("s1.endsWith(\"ef\") : "+s1.endsWith("ef"));
  //특정 문자나 문자열이 몇번째 글자인지 조회
  String s4 = "abc abc abcdef";//a : 0, 4, 8
  int idx = s4.indexOf("a");        
  System.out.println("s4.indexOf(\"a\") : "+idx); //찾아서 a를 딱 찾으면 그 index만 리턴
  System.out.println("s4.indexOf(\" abc\") : "+s4.indexOf(" abc")); //공백 index는 3번에 있다
  //뒤에서부터 조회
  System.out.println("s4.lastIndexOf(\"a\") : "+s4.lastIndexOf("a"));//뒤에서 부터 a를 찾으면 8번이 된다.
  System.out.println("s4.lastIndexOf(\" abc\") : "+s4.lastIndexOf(" abc")); //뒤어서 부터 공백abc를 찾으면 7이 된다.
  System.out.println("s4.indexOf(\"a\", 2) : "+s4.indexOf("a", 2));//2번 index에서부터 찾기 시작
  //String 에서 특정 index의 문자를 조회
  char c = s4.charAt(5);//5번 index의 char를 return
  System.out.println("s4.charAt(5) : "+c);  //5번에 있는 문자를 리턴해서 b리턴
  //문자열 일부분을 조회
  String s5 = "안녕하세요. Hello. 반갑습니다.";
  //반 : 14 H : 7 , 12
  String ss = s5.substring(14);//14번 index 부터 끝까지
  System.out.println("s5.substring(14) : "+ss);//14번 index 부터 끝까지  결과 :  반갑습니다.
  System.out.println("s5.substring(7, 12) : "+s5.substring(7, 12));//7~12-1 결과 : Hello
  //변경 하는 메소드
  //대문자->소문자
  ss = s3.toLowerCase(); //객체가 따로 만들어 지므로 변수에 대입해야 한다. 결과 : abcde 문자열 전부 대문자로 바꾸기 ctrl + shift + x, 소문자로 바꾸기 ctrl + shift + y
  System.out.println(s3+","+ss);
  //소문자 -> 대문자
  ss = s1.toUpperCase();
  System.out.println(s1+","+ss);
  //특정 char를 다른 char로 변경
  String s6 = "ababaaabb";
  //'a' -> 'k'
  ss = s6.replace('a', 'k');
  System.out.println(s6+","+ss);
  //특정 문자열을 다른 문자열로 변경
  ss = s5.replaceAll("Hello", "헬로");
  System.out.println(s5+","+ss);
  String s7 = "사과.배.귤,포도,딸기,메론,바나나";
  //String [] fruit = s7.split("\\.");
  String [] fruit = s7.split(",");
  //String [] fruit = s7.split(" ");
  System.out.println("------split() : 과일들----");
  for(String str : fruit){
   System.out.println(str);
  }

 }
}
//StringTest.java

-----------
================================================================

* project : day23
  package : string
  class : GetExention


package string;

public class GetExtention {

 public static void main(String[] args) {
  // command line argument로 파일명.확장자를 받아서 확장자만 출력하는 로직 구현
  // abc.txt -> txt
  // System.out.println(args[0]);
  System.out.println(args[0]);
  if(args.length!=1){
   System.out.println("사용법 : java GetExtension");
   return ;
  }
  String fileName = args[0];
  
  int idx = args[0].lastIndexOf(".");
  if(idx !=-1){
  String str = args[0].substring(idx+1);
  System.out.println(str);

  }else{
   System.out.println("확장자가 없습니다.");
  }
 }

}


------------------------
===========================================================================


* StringBuffer --
                 |->문자열을 다루기(변경) 위한 class
  StringBuilder--
  (->String을 만들기위해서 만든것)

String s = "abc";
String s2 = s.concat("def");

StringBuffer sb = new StringBuffer("abc");
sb.append("def");

system.out.println(sb); //결과 : abcdef

* 문자열을 붙일때는 String을 사용하면 여러개의 객체가 생겨서 좋지 않고, 임시적으로 데이터를 저장하기 위해서는 StringBuffer가 좋다. (중간에 문자열을 바꿔나갈때는 StringBuffer가 좋다. 결과는 마지막에 String에 담아 주면 된다.)

* 처음에 StringBuffer나 StringBuilder에 크기를 정해 놓고 할 수 있다. 미리 정해 두고 하는게 속도 측면에서 좋다. new StringBuffer("초기 문자열");
* 초기 문자열을 넣어두고 시작할 수 있다. new StringBuffer(10); //초기 문자열을 넣어두고 넘치면 그 글자수가 늘어난다.

'프로그래밍 > JAVA프로그래밍' 카테고리의 다른 글

난수구하기 및 수학함수  (0) 2012.07.29
java 시간 날짜 처리  (0) 2012.07.29
boxing, unboxing, wrapperClass  (0) 2012.07.29
object클래스  (0) 2012.07.29
제너릭  (0) 2012.07.29
Posted by 조은성
,

* 프리미티브 타입

char - Character
int - Integer
long - Long
double - double
float - float
byte - Byte
short - short
boolean - Boolean

* boxing : primitive - > Wrapper객체화
생성자의 argument로 넣어 객체 생성.
ex:
   new Integer(10);
   new Integer("10");// 숫자로 받을 수 있는 문자열도 넣을 수 있다.
   new Long(l); //long, double, float... 다 마찬가지로 숫자와 문자열을 넣을 수 있다.

- unboxing :  Wrapper객체 -> primitive
       wrapper객체.xxxValue();//xxx에는 primitive type이 온다.

int i = in.intValue();
long l = ln.longValue();

jdk1.5버전 이상부터는 자동으로 일어난다.
- autoboxing
int i = 10;
Integer in = new Integer(i);
Integer in = i;
Long l = 10L;

 

- autounboxing
Integer in = new Integer(10);
int i = in.intValue();
int i = in;

*
project : day22
package : wrapper
class : WrapperTest


package wrapper;

import java.util.ArrayList;

public class WrapperTest {
 public static void boxingUnboxingTest(){
  //boxing : primitive -> 객체(Wrapper)
  int i=10;
  Integer in = new Integer(i);
  Boolean b = new Boolean(false);
  Long l = new Long("10");
  //unboxing : Wrapper 객체 -> primitive
  int j = in.intValue();
  boolean b2 = b.booleanValue();
  long l2 = l.longValue();
  System.out.println(in+" - "+j);
 }
 public static void autoBoxingUnboxing(){
  //auto boxing
  Integer in =10;
  Boolean b1 = true;
  
  //auto unboxing
  int i = in;
  boolean b = b1;
  
  ArrayList list = new ArrayList();
  list.add(20);//Integer객체
  list.add(50L);//Long 객체
  list.add(false);//Boolean 객체
  int j = (Integer)list.get(0);
  long l = (Long)list.get(1);
  boolean b2 = (Boolean)list.get(2);
  ArrayList<Integer> list2 = new ArrayList<Integer>();
  list2.add(10);
  list2.add(20);
  int k = list2.get(0);
  //향상된 for문으로 list 출력
  for(Object o : list){
   System.out.println(o);
  }
 }
 public static void StringToWrapper(){
  //문자열 값을 Wrapper 객체에 넣기.
  //Integer in = "10";
  Integer in = new Integer("10");
  int i = in;
  Boolean b1 = new Boolean("false");
  //Long l1 = new Long("abcde");//숫자형태가 아니기 떄문에 컴파일 시점에는 괜찮지만 실행시점에서 에러가 난다.
  //Long l1 = new Long("10abcde");
  Long l1 = new Long("10");
  //String -> primitive
  //WrapperClass.parseXXXX(xxxx); XXXX프리미티브
  int r = Integer.parseInt("20030");
  double d = Double.parseDouble("2030.12");
  boolean b = Boolean.parseBoolean("false");
  //float f = Float.parseFloat("abcde"); //숫자로 바꿀수 없기때문에 컴파일은 되도 실행시점에서 오류가 난다. 숫자로 바꿀수 있는 문자열을 넣어야 한다.
  //char c = Character.parseChar("a");//이런건 없다.
  char c = "a".charAt(0);
 }
 public static void main(String[] args) {
  boxingUnboxingTest();
  autoBoxingUnboxing();
  StringToWrapper();
 }
}

'프로그래밍 > JAVA프로그래밍' 카테고리의 다른 글

java 시간 날짜 처리  (0) 2012.07.29
String class, String buffer  (0) 2012.07.29
object클래스  (0) 2012.07.29
제너릭  (0) 2012.07.29
collection값 빼오기  (0) 2012.07.28
Posted by 조은성
,

* Object class
- java.lang.Object : 모든 class의 최상위->모든 객체의 type이 될 수 있다.

* Object class는 추상적이어서 여기 있는 메소드를 직접 사용하는게 중요한게 아니라 하위 클래스에서 오버라이딩 해서 사용하는 것이 중요하다.
* +toString() : String -> 객체(Object)를 String으로 변환
- 메서드 이름이 객체.toXXXX()로 되면
to -> 변환

ex :
ProductDTO p = new ProductDTO();
p.toString(); <- p객체를 String으로 바꿔라.
* class이름@16진수 "ProductDTO@a567.." 이런식으로 바꿔준다. @a567...은 hashCode(객체의 가상의주소)로 바꿔준다.
->Object 타입의 toString()은 사용하지 않는다. 중요한 것은 오버라이딩 해서 사용하는 것이 중요한 것이다.
->toString()을 오버라이딩 할 시에는 Attribute들을 문자열로 return해줌.
(대표적인 toString()오버라이드한 객체들 String, StringBuffer, WrapperClass, Collection)

*equals(obj : Object) : boolean
- 매개변수로 받은 객체가 같은 객체인지 비교
ex)  obj1.equals(obj2); -> obj1==obj2


- overriding : 두객체의 attribute의 값이 같다면 true 리턴

equals overriding
public boolean equals(Object obj){
 1. obj가 null인지
 2. obj가 같은지
 3. 속성값들이 같은지
}
- equals()메소드를 오버라이딩 할때 반드시 hashCode()메소드도 같이 overriding한다.
-> + int hashCode()도 오버로딩 해야함.

o1.equals(o2); ==> true 면
o1.hashCode() ==> attribute가 같으면 hashCode()도 같게 나오게 해야한다.
o2.hashCode() ==> 디 둘도 true가 나와야 같은 객체라 생각한다.

* 값을 비교할때 equals를 쓴다. 따라서 attribute가 같으면 같은 객체다. equals메소드가 true가 나오고 hashCode()값도 true가 나와야 같은 객체다.
(equals overriding하면 hashCode()도 오버라이딩 해라.

project : day22
package : object.method
class :  ProductDTO

 

package object.method;

public class ProductDTO {
 private String productId;
 private String productName;
 private int price;
 private String productMaker;
 
 //생성자
 public ProductDTO() {
 }
 public ProductDTO(String productId, String productName, int price,
   String productMaker) {
  this.productId = productId;
  this.productName = productName;
  this.price = price;
  this.productMaker = productMaker;
 }
 
 //getter/setter
 public String getProductId() {
  return productId;
 }
 public void setProductId(String productId) {
  this.productId = productId;
 }
 public String getProductName() {
  return productName;
 }
 public void setProductName(String productName) {
  this.productName = productName;
 }
 public int getPrice() {
  return price;
 }
 public void setPrice(int price) {
  this.price = price;
 }
 public String getProductMaker() {
  return productMaker;
 }
 public void setProductMaker(String productMaker) {
  this.productMaker = productMaker;
 }
 //toString()
 @Override
 public String toString() {
  return "ProductDTO [productId=" + productId + ", productName="
    + productName + ", price=" + price + ", productMaker="
    + productMaker + "]";
 }
 //equals(), hashCode()
 @Override
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result + price;
  result = prime * result
    + ((productId == null) ? 0 : productId.hashCode());
  result = prime * result
    + ((productMaker == null) ? 0 : productMaker.hashCode());
  result = prime * result
    + ((productName == null) ? 0 : productName.hashCode());
  return result;
 }
 @Override
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  if (getClass() != obj.getClass())
   return false;
  ProductDTO other = (ProductDTO) obj;
  if (price != other.price)
   return false;
  if (productId == null) {
   if (other.productId != null)
    return false;
  } else if (!productId.equals(other.productId))
   return false;
  if (productMaker == null) {
   if (other.productMaker != null)
    return false;
  } else if (!productMaker.equals(other.productMaker))
   return false;
  if (productName == null) {
   if (other.productName != null)
    return false;
  } else if (!productName.equals(other.productName))
   return false;
  return true;
 }
}


-----------------

package object.method;

import java.util.HashSet;

public class TestEquals {
 public static void main(String[] args) {
  ProductDTO pto1 = new ProductDTO("p-1","TV",2000,"LG");
  ProductDTO pto2 = new ProductDTO("p-1","TV",2000,"LG");
  System.out.println("pto1 == pto2 - >"+(pto1==pto2));//객체의 주소값 비교
  boolean flag = pto1.equals(pto2);
  System.out.println("pto1.equals(pto2) -> "+flag);
  HashSet set = new HashSet(); //중복허용 X
  set.add(pto1);
  set.add(pto2);
  System.out.println(set);//equals와 hashCode를 둘다 오버라이딩 해야 같은 객체로 판단한다.
 }
}

'프로그래밍 > JAVA프로그래밍' 카테고리의 다른 글

String class, String buffer  (0) 2012.07.29
boxing, unboxing, wrapperClass  (0) 2012.07.29
제너릭  (0) 2012.07.29
collection값 빼오기  (0) 2012.07.28
map실습  (0) 2012.07.28
Posted by 조은성
,

* 제너릭 -1.5 : class에 사용할 type - class 작성 X
                                    - 사용시점에 지정 - O


ex :

A<String> a = new A<String>();

class A<String>{
 public void go(String a){
 }
}


위처럼 하면 A<String> a = new A<String>();
a.go();<-를 하면 String 값을 넘기는 것 밖에 안된다.
* 제너릭을 사용하지 않으면 실행은 잘되는데 컴파일 시점에 문제가 생길 수 있다.
제너릭을 쓰는 이유 Object 타입으로 썼을 경우 다른 객체들이 들어오는 건 장점이기도 하지만, 형변환시 문제가 생길 수 있기에 사용한다.
(타입에 대한 불안정을 해결해 준다.)


Project : day22
package : generic
class :   GenericTest


package generic;
class BasicGeneric<E , K>{
 
 public void printInfo(E obj){
//  if(obj instanceof String){
//  String str = (String)obj;
//  }
  System.out.println(obj);
 }

 public void test(K k){
  
 }
}
public class GenericTest {
 public static void main(String[] args) {
  BasicGeneric<String,String> b = new BasicGeneric<String,String>();
  b.printInfo("abcde");
  //b.printInfo(new Integer(10));
  BasicGeneric<Integer,String> b2 = new BasicGeneric<Integer,String>();
  b2.printInfo(new Integer(10));
 // b2.printInfo("abcde");
  BasicGeneric b3 = new BasicGeneric();//BasicGeneric<Object> b2 = new BasicGeneric<Object>();
  b3.printInfo("abcde");
  b3.printInfo(new Integer(20));
 }
}

-----------------
=============================================


Project : day22
package : generic
class :   CollectionGeneric

package generic;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

public class CollectionGeneric {
 public static void main(String[] args) {
  ArrayList<String> list = new ArrayList<String>();
  list.add("String1");
  list.add("String2");
  //list.add(new Integer(10));
  //list.add(new CollectionGeneric());
  String str = list.get(0);
  
  for(String o : list){
   System.out.println(o); 
  }
  //////////map//////////
  HashMap<String,Integer> map = new HashMap<String,Integer>();
  //map.put("name", "홍길동");
  map.put("age", 10);
  map.put("age", new Integer(20));
  Integer age = map.get("age");
  Set<String> keys = map.keySet();
  Iterator<String> itr = keys.iterator();
  while(itr.hasNext()){
   String key = itr.next();
   Integer value = map.get(key);
   System.out.println(key+"-"+value);
  }
 }
}

'프로그래밍 > JAVA프로그래밍' 카테고리의 다른 글

boxing, unboxing, wrapperClass  (0) 2012.07.29
object클래스  (0) 2012.07.29
collection값 빼오기  (0) 2012.07.28
map실습  (0) 2012.07.28
ArrayList실습  (0) 2012.07.28
Posted by 조은성
,

* 값 빼오는 패턴
1. 배열 - arr

for(int idx = 0;idx<arr.length;idx++)
{
 arr[idx];
}

2. List( ArrayList ) - list

for(int idx = 0; idx <list.size(); idx++){
 Object obj = list.get(idx); 
 
}

3. Set - set

Iterator itr = set.iterator();
while(itr.hasNext()){
 Object obj = itr.next();
}

1.5버전 이상일때는 향상된 for문도 된다
for(Object o : set){
 Object obj = o;
}

4. Map - map

Set keys = map.keySet();
Iterator itr = keys.iterator();
while(itr.hasNext()){
 Object key = itr.next();
 Object value = map.get(key);
}

'프로그래밍 > JAVA프로그래밍' 카테고리의 다른 글

object클래스  (0) 2012.07.29
제너릭  (0) 2012.07.29
map실습  (0) 2012.07.28
ArrayList실습  (0) 2012.07.28
5개의 로또번호 출력하기 - collection실습  (0) 2012.07.28
Posted by 조은성
,