MyTv2 t = new MyTv2();

t.setChannel(10);
System.out.println("CH:"+ t.getChannel());

t.setVolume(20);
System.out.println("VOL:"+ t.getVolume());

 

class MyTv2 {
    int ch;
    int vol;

    // setter
    void setChannel (int n) {
        ch = n;
    }

    void setVolume (int n) {
        vol = n;
    }

    // getter
    int getChannel() {
        return ch;
    }

    int getVolume() {
        return vol;
    }
}

 

실행결과

Class란?

- 객체(변수)를 사용하기 위한 설계도

- 형식:

class 클래스명 {
	변수 선언부
    ...
    함수(method) 선언부	// method == 클래스에 소속되어 있는 함수
}

 

- 클래스 객체를 선언(생성):

클래스명 객체(변수) = new 클래스명(); // new == 동적 할당

// 예시 
MyClass cls = new MyClass();	// 변수 == 객체(instance, object)를 선언

MyClass[] clsArr = new MyClass[10];	// 클래스 배열 선언

 


1. 클래스 정의

- 키워드: class

- 클래스 이름은 대문자로 시작하는 것이 관례임.

public class MyClass {
    // 속성(변수)
    int number;
    String text;

    // 생성자
    public MyClass(int number, String text) {
        this.number = number;
        this.text = text;
    }

    // 메서드
    public void display() {
        System.out.println("Number: " + number + ", Text: " + text);
    }
}

 

1-2. 접근 제어자

  • public: 모든 클래스에서 접근 가능
  • private: 같은 클래스 내에서만 접근 가능
  • protected: 같은 패키지 내 또는 자식 클래스에서 접근 가능
  • default(아무 것도 기입하지 않음): 같은 패키지 내에서만 접근 가능

 

1-3. 필드와 메서드

  • 필드: 클래스의 속성으로, 객체의 상태를 나타냅니다. // 변수 선언부
  • 메서드: 클래스의 기능으로, 객체가 수행할 수 있는 작업을 정의합니다. // 메소드 선언부

 

2. 객체 생성

- 클래스를 정의한 후, 그 클래스를 기반으로 객체를 생성할 수 있음.

public class Main {
    public static void main(String[] args) {
        // MyClass 클래스의 객체 생성
        MyClass myObject = new MyClass(10, "Hello");
        
        // 메서드 호출
        myObject.display();
    }
}

 

3. 생성자

생성자는 객체가 생성될 때 호출되는 특별한 메서드입니다. 생성자는 클래스 이름과 동일하며 반환 타입이 없습니다. 기본 생성자와 매개변수가 있는 생성자를 정의할 수 있습니다.

public class MyClass {
    int number;

    // 기본 생성자
    public MyClass() {
        number = 0;
    }

    // 매개변수가 있는 생성자
    public MyClass(int number) {
        this.number = number;
    }
}

 

 

4. 상속

Java에서는 클래스가 다른 클래스를 상속받아 기능을 확장할 수 있습니다.

public class Animal {
    public void eat() {
        System.out.println("Eating...");
    }
}

public class Dog extends Animal {
    public void bark() {
        System.out.println("Barking...");
    }
}

// 사용 예
Dog myDog = new Dog();
myDog.eat(); // 상속된 메서드 호출
myDog.bark(); // Dog 클래스의 메서드 호출

 

 

5. 인터페이스

인터페이스는 클래스가 구현해야 하는 메서드의 집합을 정의합니다. 다중 상속을 지원합니다.

public interface Animal {
    void eat();
}

public class Dog implements Animal {
    public void eat() {
        System.out.println("Dog is eating.");
    }
}

 

6. 패키지

클래스를 그룹화하여 관리할 수 있도록 패키지를 사용할 수 있습니다. 패키지는 package 키워드로 정의합니다.

package mypackage;

public class MyClass {
    // ...
}

 

 

7. 예외 처리

클래스 내에서 발생할 수 있는 예외를 처리하기 위해 try-catch 문을 사용합니다.

public class MyClass {
    public void riskyMethod() {
        try {
            // 위험한 코드
        } catch (Exception e) {
            System.out.println("예외 발생: " + e.getMessage());
        }
    }
}

수행할 내용:

1. 파일명 ?을 입력 받아서 파일을 생성하고

2. 회원 ?명의 이름을 입력받아 작성한다

3. 파일로부터 모든 회원을 읽어들여 String 배열에 저장하고, 출력하기

 

import java.io.*;
import java.util.Arrays;
import java.util.Scanner;

public class Work1 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        /*
            파일명을 입력 받아 작성하고
            파일에 회원 ?명을 입력받아 작성한다
            파일로부터 모든 회원을 읽어 들여 String 배열에 저장한다
         */

        // 파일명을 입력 받아 작성
        System.out.print("생성할 파일명 입력 >>> ");
        String user_input = sc.next();
        String fileDir = "e:\\" + user_input + ".txt";
        File newFile = new File(fileDir);

        // 파일에 회원 ?명을 입력받아 작성
        System.out.print("입력할 회원수 입력 >>> ");
        int user_input_num = sc.nextInt();

        for (int i=0; i<user_input_num; i++) {
            System.out.print("회원명 입력 >>> ");
            String st = sc.next();
            try {
                FileWriter fw = new FileWriter(newFile, true); // append 모드로 열기
                fw.write(st + "\n");
                fw.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        // 파일로부터 모든 회원을 읽어 들여 String 배열에 저장
        try {
            FileReader fr = new FileReader(newFile);
            BufferedReader br = new BufferedReader(fr);

            // 데이터 읽어오기
            String names = "";
            String str = "";

            while ((str = br.readLine()) != null){
                names = names + str + "-";
            }
            br.close();

            names = names.substring(0, names.length()-1);   // 맨 끝에 붙은 토큰 제거 => .substring(시작 인덱스, 끝 인덱스)

            String[] nameArr = names.split("-");

            System.out.println(names);
            System.out.println(Arrays.toString(nameArr));

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

    }
}

Exception = 예외 (error와는 다르다)

[1] 자주 사용되는 Exception

  • number 의 경우 Format
  • array 의 경우 index out of bounds
  • class 의 경우 class not found
  • file 의 경우 file not found

[2] return은 함수 내에서 break 처럼 쓰일 수 있음

 

[3] 예외가 발생할 수 있는 코드를 포함한 함수를 처리할 때,

그 함수 내부에서 try-catch를 사용하지 않는 대신, throws를 던지는 방법이 있음.

그 이후, 해당 함수가 호출되는 곳에서 try-catch로 잡을 수 있음.

 

[4] 여러 세분화된 예외 클래스들을 모두 기억할 필요 없고, (Exception e) 하나로 다 잡히는 편임

try - catch - (finally) 구문 형식

            try {
                처리코드1 (예외가 나올 가능성 있는 코드)
                처리코드2 (예외가 나올 가능성 있는 코드)

            } catch(예외 클래스1) {
                예외가 나온 경우 처리

            } catch(예외 클래스2) {

            } finally {
                // finally는 생략 가능
                // try문에 진입하면 맨 마지막에 무조건 실행됨
                반드시 해야 될 뒷처리
            }

 

 

코드 예시 - 1

int[] array = { 1, 2, 3 };

System.out.println("프로그램 시작");

try {
    for (int i = 0; i < 3; i++) {
        System.out.println(array[i]);
    }
} catch(ArrayIndexOutOfBoundsException e) {
    System.out.println("배열 범위 초과");
    //e.printStackTrace();
    //System.out.println(e.getMessage());
    //return;     // <- main 함수도 void 함수이고, 여기에서 딱 튕겨나감
} catch (NumberFormatException e) {
    e.printStackTrace();
} finally {     // 문제가 있든 없든 무조건 거쳐간다
    System.out.println("무조건 처리!!!");
}

System.out.println("프로그램 끝");

 

 

코드 예시 2 - return을 제어문처럼 (break문) 사용하는 경우

function(3);
function(0);
static void function(int i) {
    if (i ==0) {
        System.out.println("i==0 이므로 다음 처리를 하지 않습니다.");
        return;
    }

    //if (i == 0) return;         // 이 함수를 빠져나가도록 함. return은 함수 계의 break문

    System.out.println("processing~~~");
}

 

 

코드 예시 3 - 함수에서 throws 를 던지고, 함수 밖에서 try-catch를 받는 경우

public class Sample1 {
    public static void main(String[] args) {
        try {
            excFunction();
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("함수안의 예외");
        }
	}
    // throws -- 예외가 발생할 수 있는 코드라고 명시
    // throws가 있으면 -> 외부에서 try catch를 붙여라

    static void excFunction() throws ArrayIndexOutOfBoundsException {
        int[] array = { 1, 2, 3 };
        /*try {
            for (int i = 0; i < 4; i++) {
                System.out.println(array[i]);
            }
        } catch (ArrayIndexOutOfBoundsException e) {
            e.printStackTrace();
        }*/
        for (int i = 0; i < 4; i++) {
            System.out.println(array[i]);
        }
    }
}

 

 

대표적인 예외 처리 5가지

  • NullPointerException
  • ArrayIndexOutOfBoundsException
  • FileNotFoundException
  • NumberFormatException
  • InputMisMatchException
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
import java.util.Scanner;

public class Sample2 {
    public static void main(String[] args) {
        /*
            Exception : 예외
            총 5가지 정도가 대표적인 예외
         */

        // NullPointerException
        // int[] array = new int[5]; // 힙 영역에 있음
        int[] array = null; // 메모리 초기화 (힙 영역에 없음)

        try {
            System.out.println(array.length);
        } catch (NullPointerException e) {
            System.out.println("배열이 할당되어 있지 않습니다");
        }

        // ArrayIndexOutOfBoundsException
        int[] array1 = { 1, 2, 3 };
        try {
            System.out.println(array1[3]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("배열 범위를 초과하였습니다");
        }

        // FileNotFoundException
        File file = new File("C:\\xxx.txt");
        FileInputStream is;

        try {
            is = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            //throw new RuntimeException(e);
            System.out.println("파일이 존재하지 않습니다.");
        }

        // NumberFormatException
        try {
            int num = Integer.parseInt("123o3");
        } catch (NumberFormatException e) {
            System.out.println("잘못된 형식을 입력하였음.");
        }

        // InputMismatchException
        Scanner sc = new Scanner(System.in);

/*        try {
            System.out.print("number 입력 >>> ");
            int number = sc.nextInt();
            System.out.println("입력 후 실행");
        } catch (InputMismatchException e) {
            System.out.println("숫자 이외의 문자를 입력하였음");
        }*/

/*        while (true) {
            boolean b = true;
            System.out.print("숫자를 입력 >>> ");
            String numStr = sc.next();
            for (int i = 0; i < numStr.length(); i++) {
                int asc = numStr.charAt(i);     // 한글자씩 산출
                if (asc < 48 || asc > 57) {
                    b = false;
                }
            }
            if (b) break;
            System.out.println("잘못 입력하셨습니다. 다시 입력해주세요.");
        }

        int number = Integer.parseInt(numStr);
*/

        boolean b = true;
        while (true) {
            try {
                System.out.print("숫자를 입력 >>> ");
                int number = sc.nextInt();
                b = true;
                break; // 정상적으로 숫자가 입력되면 루프 종료
            } catch (InputMismatchException e) {
                System.out.println("숫자가 아닙니다");
                b = false;
                sc.next(); // 잘못된 입력을 버퍼에서 제거 - 버퍼 비우지 않으면 무한루프에 빠짐
            }
        }
    }
}

 

NullPointer? 포인터?

Java의 메모리 구조는 4 영역으로 나뉨

>> Stack , Heap , Static , Sys

 

Stack 영역에서 변수명을 저장하고 있고,

Heap 영역에서 변수명이 가리키는 데이터를 가지고 있다. (주소값이 여기에 있음)

 

그런데 만약 이런 경우를 생각해보자.

int[] array = null;

이 경우에는 heap 영역에 메모리 공간이 할당되지 않았기 때문에 array는 null을 참조하고 있게 된다.

여기에서 NullPointerException이 발생하게 되는 것임.

 

  • 파일에 쓰기 = 파일에 출력하기 = 기록하기
  • 만약 파일이 없는 경우 (자동) 생성 후에 쓰기 작업이 됨
  • 만약 파일이 있었다면, 덮어쓰기가 된다

쓰기 (Write)

1. 한 문장씩 쓰기

: FileWriter

File file = new File("e:\\test.txt");

String str = "반갑습니다";

try {
    // 쓰기 작업 (덮어쓰기 됨; 매번 새로 쓰기)
    FileWriter fw = new FileWriter(file);   // fw는 접근자
    fw.write(str + "\n");
    fw.close();     // 반드시 닫아주어야 함!!
    
} catch (IOException e) {
    throw new RuntimeException(e);
}

 

1-2. 이어서 쓰기 (append)

: FileWriter

// 추가 쓰기 작업
FileWriter fw = new FileWriter(file, true);     // append = 추가
fw.write("건강하세요");
fw.close();

 

2. 문장으로 쓰기

: FileWriter + BufferedWriter + PrintWriter

// 문장으로 쓰기
String[] strArr = { "홍길동", "성춘향", "일지매" };
try {
    FileWriter fw3 = new FileWriter(file);
    BufferedWriter bw = new BufferedWriter(fw3);    // Buffer = 저장공간
    PrintWriter pw = new PrintWriter(bw);

    /*pw.println("하이");
    pw.println("건강하세요");
    pw.println("성공하세요");*/

    for (String s: strArr) {
        pw.println(s);
    }

    pw.close();             // 반드시 닫아주기

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

 

 

파일 읽기

1. 한 문자씩 읽기

FileReader

File file = new File("E:\\test.txt");

// 한 문자씩 읽기
try {
    FileReader fr = new FileReader(file);

    String str = "";
    int c = fr.read();

    // 파일의 끝부분까지 읽어오기 -> 루프 사용
    while ( c != -1) {      // -1은 파일의 끝임.
        str = str + (char)c;    // 읽어오고서,
        c = fr.read();          // 데이터 갱신
    }
    fr.close();     // '읽기' 작업에서는 close가 덜 중요함
    System.out.println(str);
} catch (FileNotFoundException e) {
    // 파일 '쓰기'는 파일이 없으면 새로 생성하지만,
    // 파일 '읽기'는 파일이 없으면 읽어올 수 없음!
    throw new RuntimeException(e);
} catch (IOException e) {
    // .read() 메소드에서도 예외 처리 필요
    throw new RuntimeException(e);
} catch (Exception e) {
    // 포괄 예외 처리 Exception
    throw new RuntimeException(e);
}

 

 

2. 문장 단위로 읽기 : readLine

FileReader

BufferedReader

 

// 문장으로 읽기
try {
    FileReader fr = new FileReader(file);
    BufferedReader br = new BufferedReader(fr);

    String str = "";
    // 첫번째 방법
    String names = "";
    while ((str = br.readLine()) != null) {
        //System.out.println(str);
        names = names + str + "\n";
    }
    br.close();

    //System.out.println(str);
    System.out.println(names);

} /*catch (FileNotFoundException e) {
    throw new RuntimeException(e);
}*/ catch (Exception e) {
    throw new RuntimeException(e);
}

1. 파일명 + 디렉토리(폴더)명 검색하기

  • .listFiles() : 배열로 반환
  • .getNames()
    // 파일 + 디렉토리 (폴더) 검색
    File fileDir = new File("C:\\");

    // 각 파일의 정보를 취득
    // 외부에 보이지 않도록 만든 폴더의 이름도 나옴
    File[] fileList = fileDir.listFiles();
    for (int i=0; i< fileList.length; i++) {
        if (fileList[i].isFile()) {         // 파일인 경우
            System.out.println("[파일] " + fileList[i].getName());
        } else if (fileList[i].isDirectory()) {     // 폴더인 경우
            System.out.println("[폴더] " + fileList[i].getName());
        } else {
            System.out.println("[?] " + fileList[i].getName());
        }
    }

 

 

2. 파일 생성하기

  • 경로와 파일이름 지정 후
  • .createNewFile()
    // 경로와 파일 이름 지정
    File newFile = new File("E:\\newfile.txt");

	// 파일 생성하기 .createNewFile()
    try {
        if (newFile.createNewFile()) {
            System.out.println("파일 생성 성공!");
        } else {
            System.out.println("파일 생성 실패!");
            // 보안이 걸려있거나
            // 이미 같은 이름의 파일이 존재하거나
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

 

 

3. 파일의 존재 여부 확인하기

  • 지정된 경로 + 파일명을 가진 파일이 있는지 확인
  • .exists()  : boolean 반환함
    File newFile = new File("E:\\newfile.txt");

    if (newFile.exists()) {
        System.out.println("파일이 존재합니다.");
    } else {
        System.out.println("파일이 존재하지 않습니다.");
    }

 

 

4. 파일의 읽기 가능 여부

  • .canRead()
    // File newFile = new File("E:\\newfile.txt");
    
    // 파일의 읽기 여부
    if (newFile.canRead()) {
        System.out.println("파일의 읽기가 가능합니다.");
    } else {
        System.out.println("파일의 읽기가 가능하지 않습니다.");
    }

 

 

4-1. 파일을 읽기 전용으로 전환시키기

  • .setReadOnly()
  • 읽기 전용으로 전환시키면, 이후에 외부에서 접근해도 편집후저장이 막힘.
//File newFile = new File("E:\\newfile.txt");

newFile.setReadOnly();

 

 

5. 파일의 쓰기 가능 여부

  • .canWrite()
    //File newFile = new File("E:\\newfile.txt");

    if (newFile.canWrite()) {
        System.out.println("파일 쓰기가 가능합니다.");
    } else {
        System.out.println("파일 쓰기를 할 수 없습니다.");
    }

 

 

6. 파일 삭제하기

  • .delete()
    //File newFile = new File("E:\\newfile.txt");
    // 파일 삭제
    if (newFile.delete()) {
        System.out.println("파일이 삭제되었습니다.");
    } else {
        System.out.println("파일이 삭제되지 않았습니다.");
    }

+ Recent posts