* 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 조은성
,