이론

예외(Exception)

  • 프로그램 진행중 예외가 발생했을 때 프로그램이 종료되지만,가벼운 예외이거나 예상하고 있던 예외인 경우 예외처리를 해주어서프로그램의 비 정상적인 종료를 막고 정상적으로 프로그램을 계속 진행할 수 있도록 해줌
    실행예외(RunTimeException)-컴파일러가 체크하진않지만 실행상의 에러에 대비하여 처리
    예외(Exception)-컴파일러가 체크하여 예외처리가 없으면 실행안됨,반드시작성해야만컴파일

  • RuntimeException -컴파일시에는 문제가없지만 실행할때 문제가 발생하는 경우

  • NullPointerExceiption - 생성하지 않고 클래스의 메소드를 호출하는 경우
    ;객체참조가 없는상태 즉NULL값을 갖는 참조변수로 객체접근을 햇을때발생

  • NumberFormatExcetpion - 입력한 데이터의 형식 오류(숫자입력시 문자가 포함된 경우)

  • ArrayIndexOutOfBoundsException - 문자열의 인덱스에 대한 오류(특정 배열의 인덱스를 벗어난 경우?)-배열에서 인덱스범위를 초과하여 사용할 경우

<Java에서 파일읽기>
1. FileReader
2. BufferReader
3. Scanner
4. Files


기본 예제

package Day0703;

public class ExException_01 {

    public static void main(String[] args) {

        System.out.println("프로그램 시작!!!");
        try { // 에러 발생할 수 있는 가능코드
            int num = 3 / 0; // 정수를 0으로 나누면 무조건 에러발생.
        } catch (ArithmeticException e) { // 에러에 대한 해결(처리)
            System.out.println(e.getMessage()); // 예외처리에 대한 처리 방법(ex. 예외처리 메세지)
//            e.printStackTrace(); // 에러에 대한 자세한 예외 정보 출력.
        }
        System.out.println("프로그램 종료!!!");
    }
}

결과

프로그램 시작!!!
/ by zero
프로그램 종료!!!

예제2

package Day0703;

import java.util.Date;

public class NullPoint_02 {

    Date date;
// NullPointerException - 생성하지 않고 클래스의 메소드를 호출하는 경우
    public void writeday() {
        int y,m,d;
        try {
            y = date.getYear() - 1900;
            m = date.getMonth() + 1;
            d = date.getDate();

            System.out.println(y + "년 " + m + "월 " + d + "일 입니다.");
        }
        catch (NullPointerException e) {
            System.out.println("객체생성을 안했어요"+e.getMessage());
        }
    }

    public static void main(String[] args) {

//        Deprecated ??
        NullPoint_02 np=new NullPoint_02();
        np.writeday();
        System.out.println("***정상 종료***");
    }
}

결과

객체생성을 안했어요Cannot invoke
"java.util.Date.getYear()" because "this.date" is null
정상 종료

예제3

package Day0703;

import java.io.IOException;
import java.io.InputStream;

public class FileException_03 {

    public static void main(String[] args) {
    // 뒤에 Stream이라고 붙은 것은 문자화 못함. 원시문자임.
    // writer 로 붙은건 한글, 영어화 가능
        InputStream is=System.in;

        int a=0;

        System.out.println("한글자 입력: ");
        try {
            a=is.read(); // 읽어오는거
        } catch (IOException e) {
            // throw new RuntimeException(e);
            System.out.println("오류: "+e.getMessage());
        }
        System.out.println("3초 뒤 출력");

        try {
            Thread.sleep(3000); // 1초에 값이 1000, 즉 3000은 3초다. // 느리게 출력
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("입력값: "+(char)a);
    }
}

결과

한글자 입력:
f
3초 뒤 출력
입력값: f

파일 불러오기(txt 파일)

  • try-catch의 경우 파일 호출을 하면 오류문이 뜬다. 해당 오류문 클릭하여 try-catch를 클릭하여 자동기입하게 해주자.
  • try 문 안에서 오류가 한번 더 뜨면 try는 안하고 catch만 추가하여 해결 가능하다
package Day0703;

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

public class FileException_04 {

    public static void read(){
        String fileName="/Users/imhyeongjun/Desktop/sist0615/file/monday.txt";
        BufferedReader br=null; // 파일 선언
        FileReader fr=null; // 문자 단위로만 읽을 수 있다.

        try {
            fr=new FileReader(fileName); // 파일 호출
            System.out.println("파일을 열었어요!!!");

            br=new BufferedReader(fr); // 호출한 파일을 BufferedReader로 가져옴
            // BufferedReader는 한줄만 읽을 수 있다.

            // 여러줄 읽어야 하므로 while문 진행
            while (true){
                // 메모장에서 내용을 한줄씩 읽어온다.
                String s=br.readLine(); // readLine은 한줄씩 읽을 수 있다.

                // 마지막 줄일경우 null값을 읽어서, null값일 경우 빠져나가기.
                if(s==null){
                    break;
                }
                System.out.println(s);
            }

        } catch (FileNotFoundException e) {
 //           throw new RuntimeException(e);
            System.out.println("파일이 없어요: "+e.getMessage());
        }
        catch (IOException e) { //try 안에서 또 try catch가 발생하면 catch만 한번 더 해주면 된다.

        }
        finally {
            try {
                fr.close();
                br.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void main(String[] args) {

        read();
        System.out.println("메모 정상종료");
    }
}

결과

파일을 열었어요!!!
파일을 열었어요!!
안녕
오늘은
월요일 이야
예외처리 공부중입니다.
메모 정상종료

예제 2

package Day0703;

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

// score.txt를 읽고 몇개인지 구하고 총점, 평균까지 구해서 출력
public class FileExcep_06 {

    public static void scoreRead(){
        String fileName="/Users/imhyeongjun/Desktop/sist0615/file/score.txt";
        FileReader fr=null;
        BufferedReader br=null;
        int cnt=0; // 총 갯수
        int total=0; // 총 합계
        double avg=0; // 평균
        // class에서는 초기값 안넣으면 null, 0으로 자동 설정
        // method 에서는 무조건 초기값을 기입해줘야 한다. 안해주면 오류남.

        // 파일 읽기
        try {
            fr=new FileReader(fileName);
            System.out.println("파일 정상적으로 읽음");

            br=new BufferedReader(fr);

            while (true){
                String s=br.readLine();

                if(s==null){ // 더이상 값이 없으면
                    break;
                }
                    cnt++; // 읽은 갯수
                    total+=Integer.parseInt(s); // 합계 '+='누적
                System.out.println(s);
            }
            // 평균구하기
            avg=(double) total/cnt;
            System.out.println("총 갯수: "+cnt);
            System.out.println("총점: "+total);
            System.out.printf("평균: %.2f",avg);

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e){

        } finally {
            // 자원은 오픈한 반대 순서로 닫는다.
            // 문 열고 들어가서 다시 뒤돌아 나오는 것으로 생각하면 된다.
            try {
                br.close();
                fr.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
    public static void main(String[] args) {
        scoreRead();
        System.out.println("\\n출력 끝");
    }
}

결과

파일 정상적으로 읽음
2324
23423
535 45
4
6
6
5
63
3636
565
656
4
5
5
6
6666
총 갯수: 17
총점: 37954
평균: 2232.59
출력 끝

split, Token (문자 분리, 문자 쪼개기)

  • 분리 1번 2번 둘 다 사용 가능한 코드들이다. 확인하고 골라서 사용하자.
package Day0703;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;

public class QuizTokenFile_09 {

    /*
***과일목록***
상품  수량  단가  총금액
------------------------
바나나 10  5000 50000
 */

    public static void fruitList(){
        String fileName="/Users/imhyeongjun/Desktop/sist0615/file/fruit.txt";
        FileReader fr=null;
        BufferedReader br=null;

        try {
            fr = new FileReader(fileName);
            br = new BufferedReader(fr);

            System.out.println("**과일목록**");
            System.out.println("상품\\t수량\\t단가\\t총금액");
            System.out.println("==========================================");

            while (true){
                String s=br.readLine(); // multi-catch

                if(s==null){
                    break;
                }

/*              // 분리 1
                StringTokenizer st=new StringTokenizer(s,",");

                // 배열의개수만큼 반복출력
                String fName=st.nextToken();
                int su=Integer.parseInt(st.nextToken());
                int price=Integer.parseInt(st.nextToken());
                int total=su*price;

                System.out.println(fName+"\\t"+su+"개\\t"+price+"원\\t"+total+"원");
*/
                // 분리 2
                String []data=s.split(",");
                String fName=data[0];
                int su=Integer.parseInt(data[1]);
                int price=Integer.parseInt(data[2]);
                int total=su*price;

                System.out.println(fName+"\\t"+su+"개\\t"+price+"원\\t"+total+"원");

            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        finally {
            try {
                br.close();
                fr.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void main(String[] args) {

        fruitList();
    }
}

결과

**과일목록**
상품 수량 단가 총금액
============================
바나나 10개 1200원 12000원
키위 20개 2000원 40000원
딸기 30개 7000원 210000원
포도 22개 9000원 198000원

FileWriter 글쓰기, text파일 생성하기

  • 이전까지는 모두 text파일을 가져오는 방법이었다면 이번건 text파일을 생성하는 방법이다.
  • 여기서 유의할점은 fw=new FileWriter(fileName) 과 fw=new FileWriter(fileName,append:true)의 차이점이다. append:true 유,무로 인해 단순 생성과 중복 생성이 바뀐다. append:true의 경우 생성된 text파일 안에 내용이 계속하여 생긴다. 위의 내이름은 홍길동 부터 서해번쩍하지 까지의 내용이 계속 반복하여 생겨 나중에는 몇백줄이 될 것이다.
package Day0704;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;

public class FileWriter_05 {

    // BufferReader 는 파일 불러올때 번역기 정도로 생각하자.
    public static void  fileWriter(){
        FileWriter fw=null; // 선언만 한거다. 생성한거 아니다.
        // 메서드는 무조건 초기값 지정 해줘야함, class는 안해줘도 됌.
        String fileName="/Users/imhyeongjun/Desktop/sist0615/file/filetest1.txt";

        try {
            fw=new FileWriter(fileName); // 파일을 새로 생성(같은 이름이 있으면 삭제하고 새로 생성해준다.)

            //파일에 내용 추가하기
            fw.write("Have a Nice Day!!\\n"); // 메모장 줄 넘김(\\n)
            fw.write(new Date().toString()); // 소스코드는 toString() 해줘야 한다.
            fw.write("\\n이성신 조장님!!");
            System.out.println("** 파일 저장 성공 **");

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                fw.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void fileWrite2(){
        FileWriter fw=null;
        String fileName="/Users/imhyeongjun/Desktop/sist0615/file/filetest2.txt";

        try {
            fw=new FileWriter(fileName,true); // 추가 모드, 실행하면 내용이 계속 추가 된다.
            fw.write("내 이름은 홍길동\\n");
            fw.write("=====================\\n");
            fw.write("동해번쩍 서해번쩍 하지");

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                fw.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void main(String[] args) {
        fileWriter();
        fileWrite2();
    }
}

결과

** 파일 저장 성공 **
profile
java를 잡아...... 하... 이게 맞나...

0개의 댓글