1. 중첩 클래스
- 내부 클래스(Inner Class)
클래스 또는 메소드 안에 또 다른 클래스를 생성하는 것
내부 클래스는 외부 클래스의 모든 멤버를 자신의 멤버처럼 사용
static 내부 클래스를 제외한 내부 클래스는 항상 외부 클래스 객체를 통해서 생성
- 로컬 클래스(Local Class)
메소드 안에서 정의된 클래스(메소드 안에서만 사용할 수 있음)
외부 클래스의 모든 멤버에 접근이 가능(private 멤버도 접근 가능)
- 정적 중첩 클래스(Static Class)
내부 클래스가 static으로 정의
외부 클래스에 관계없이 객체를 생성할 수 있음
- 익명 클래스(Anonymous Class)
클래스를 정의하지 않고 객체를 정의할 때 사용
1회용 클래스이므로 재활요이 불가능
굉장히 많이 쓰임
2. 예외 처리(Exception)
오류(error)
자바 컴파일러에 의해 문법 오류를 발생
예외(exception)
문법이 맞게 작성되었다 하더라도 프로그램을 실행하면서 예상하지 못한 오류가 발생
예측할 수 있는 예외, 예측 못하는 예외
✔ 예외가 발생하는 원인
- 사용자가 잘못된 데이터를 입력하는 경우
- 개발자가 로직이나 계산을 잘못 작성한 경우
- 하드웨어나 네트워크가 제대로 동작하지 못하는 경우
- 악의적으로 잘못된 연산을 요구하거나 시스템을 공격
예외의 종류
- 컴파일시에 예외 발생
- 런타임시에 예외 발생
[Exception]
[IOException] [FileNotFoundException] ... [RuntimeException]
예외처리 코드
try{
실제 코드가 들어가는 곳으로 예외 상황이 발생할 가능성이 있는 코드
...
예외 발생 !
.... <--- 예외가 발생하면 이곳으로 오지 않음
}catch(예외객체타입1 참조변수1){
try 블록에서 예외 객체 타입1의 Exception이 발생하면 여기로 오게 됨
해당 코드를 실행 후 에러없이 벗어남
...
}catch(예외객체타입2 참조변수2){
try 블록에서 예외 객체 타입2의 Exception이 발생하면 여기로 오게 됨
해당 코드를 실행 후 에러없이 벗어남
...
}catch(예외객체타입3 참조변수3){
try 블록에서 예외 객체 타입3의 Exception이 발생하면 여기로 오게 됨
해당 코드를 실행 후 에러없이 벗어남
...
}
...
finally{
try블록에서 Exception 발생과 관계없이 무조건 실행되는 코드(옵션)
...
}
문제.
scanner로 입력을 받아 해당 데이터가 숫자면 숫자를 출력, 문자면 -1을 출력하는 프로그램을 만들어보자
(단, 예외처리를 사용하여 작성)
강제로 예외를 발생시키는 방법
Exception 참조변수 = new Exception("예외가 발생하면 출력될 문자열");
...
...
throw 참조변수; // 예외발생!
✔ throw
강제로 예외를 발생시키고자 할 때 사용
현재 메소드의 예외를 처리한 후 상위 메소드에 예외 정보를 전달함
✔ throws
현재 메소드에서 자신을 호출한 상위 메소드로 예외를 발생시킴
사용하는 메소드를 호출한 상위 메소드에서 예외처리에 대한 책임을 맡김
3. 파일 다루기
File 클래스
파일 또는 디렉토리를 다루는 클래스
입출력 관한 작업
File 참조변수 = new File(파일 경로 또는 파일이름);
✔ 스트림(stream)
- 자바는 파일이나 콘솔의 입출력을 직접 다루지 않고 스트림이라는 흐름을 통해 다룸
- 운영체제에 의해 생성되는 가상의 연결고리를 의미하고 중간 매개자 역할을 함
Java 프로그램 <-------> OS(운영체제) <----------> 디스크(파일, 디렉토리)
모니터, 프린터, 네트워크 ...
✔ 절대 경로
물리적인 전체경로
예) D:/jsp/java/day0/day0.txt
✔ 상대 경로
현재 동작하고 있는 파일을 중심으로한 상대적인 경로
예) Day9.txt, 디렉토리명/Day9.txt, .../Dya9.txt
exists(): 파일이 실제 존재하는지 여부 리턴값 boolean타입
isDirectory(): 해당 경로가 디렉토리인지 여부
length(): 파일 데이터 길이 반환(byte), 한글은 3byte, 영어/특수문자/공백 1byte
mkdir(): 디렉토리를 생성
createNewFile(): 파일을 생성
FileInputStream 클래스
- java.io의 가장 기본이 되는 입력 클래스
- 입력 스트림을 생성
read(): 스트림을 통해 byte단위로 데이터를 읽어옴
FileOutputStream 클래스
- java.io의 가장 기본이 되는 출력 클래스
- 출력 스트림을 생성
write(): 스트림을 통해 byte단위로 데이터를 씀
FileReader 클래스
- FileInputStream과 유사
- 문자 스트림으로서 문자 단위의 바이트 변환 기능을 가지고 있음
- 바위트 단위가 아닌 문자단위로 입출력을 실행
FileWriter 클래스
- FileOutputStream과 유사
- 문자 스트림으로서 문자 단위의 바이트 변환 기능을 가지고 있음
- 바위트 단위가 아닌 문자단위로 입출력을 실행
PrintWriter 클래스
- 문자열을 출력하는 스트림 Writer 속성을 가진 클래스
- OutputStream의 자식 클래스이며 byte단위 출력 클래스인 PrintStream의 print메서드를
모두 구현하여 사용할 수 있음
과제1.
"product.txt" 에서 데이터를 읽어 product 객체에 각각 데이터를 저장하고 ArrayList에 담아
출력하는 프로그램을 작성해보자.
product.txt 내용
갤럭시노트,1200000,삼성
아이버드,130000,삼성
그램노트북,1000000,엘지
60인치TV,3000000,소니
맥북프로,1800000,애플
과제2.
어제 과제에 예외처리를 적용하여 재작성해보자.
class OuterClass {
private int num1 = 10;
public void method1(){
System.out.println("num1: " + num1);
}
public void printInner(){
InnerClass innerClass = new InnerClass();
innerClass.method2();
// innerClass.num2 = 10; //외부클래스에서 내부 클래스의 private 접근이 가능
}
public class InnerClass{ //밖에 있는 다른 클래스랑 이름 같아도 됨
private int num2 = 20;
public void method2(){
System.out.println("OuterClass.num1: " + num1);
System.out.println("InnerClass.num2: " + num2);
}
}
}
public class InnerClass {
public static void main(String[] args) {
OuterClass outerClass = new OuterClass();
outerClass.method1();
outerClass.printInner();
System.out.println();
OuterClass.InnerClass innerClass = outerClass.new InnerClass();
//내부클래스 생성하려면 먼저 외부클래스 객체 미리 생성해야함
}
}
public class LocalClass {
private int num1 = 10;
public void method1(){
//private int num2 = 20; private은 로컬안에서 사용 불가
int num2 = 20;
class Local{
private int num3 = 30; //클래스안이라 private사용 가능
private final int num4 = 40;
public void method2(){
System.out.println("num1: " + num1);
System.out.println("num2: " + num2);
System.out.println("num3: " + num3);
System.out.println("num4: " + num4);
}
}
Local local = new Local();
local.method2();
}
public static void main(String[] args) {
LocalClass localClass = new LocalClass();
localClass.method1();
}
}
public class StaticClass {
public static void print(){
System.out.println("static 메소드!");
}
static class Static1{
int num = 0;
public int add(){
num++;
return num;
}
}
public static void main(String[] args) {
print();
StaticClass.print(); // 외부에서 사용
StaticClass.Static1 static1 = new StaticClass.Static1(); //외부클래스의 객체를 안만들어도되는거네
System.out.println(static1.add());
}
}
interface Inter1{
void method1();
}
class Class1 implements Inter1 {
@Override
public void method1() {
System.out.println("Inter1을 구현한 클래스");
}
}
interface Inter2 {
String method2();
}
class Class2 implements Inter2{
@Override
public String method2() {
return "Inter2를 구현한 클래스(실명 클래스)";
}
}
class Class3 {
public void method3(Inter2 inter2){
System.out.println(inter2.method2());
}
}
public class Anonymous {
public static void main(String[] args) {
Class2 class2 = new Class2();
Class3 class3 = new Class3();
class3.method3(class2);
class3.method3(new Class2(){
@Override
public String method2() {
return "익명 클래스";
}
});
}
}
public class Exception1 {
public static void main(String[] args) {
try{
// int num =10;
// int result = num/0;
// System.out.println(result);
// String str = null;
// System.out.println(str.length());
// int[] num = new int[3];
// num[0]= 100;
// num[3]=10;
String str = "천";
System.out.println(Integer.parseInt(str));
}catch(ArithmeticException ae){
System.out.println("0으로 나눈 예외상황 발생!");
}catch(NullPointerException ne){
System.out.println("객체를 정의하지 않음!");
}catch(ArrayIndexOutOfBoundsException ae){
System.out.println("범위를 넘어섬");
}catch(NumberFormatException fe){
System.out.println("숫자로 변환하지 못함!");
}catch(Exception e){ // 전체 exception작성은 반드시 맨밑에 해줘야함
System.out.println("모든예외를 처리!");
}
System.out.println("프로그램을 정상적으로 종료합니다");
}
}
public class Exception3 {
public static void main(String[] args) {
try {
Class obj = Class.forName("com.koreait.test");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println("포로그램이 정상적으로 종료되었습니다");
}
}
public class Exception4 {
public static void main(String[] args) {
Exception e = new Exception("예외를 발생합니다!!");
try {
throw e;
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println("프로그램이 정상적으로 종료되었습니다");
}
}
public class Exception5 {
public static void main(String[] args) throws Exception{
method1();
}
public static void method1() throws Exception{
method2();
}
public static void method2() throws Exception{
method3();
}
public static void method3() throws Exception{
System.out.println("method3() 호출!");
Exception e = new Exception("예외발생");
throw e;
}
}
import java.io.File;
import java.io.IOException;
public class FIle1 {
public static void main(String[] args) {
//File클래스의 기본적인 파일 생성법
//파일 객체에 대한 생성 및 접근
File file1 = new File("input1.txt");// 실존하는파일이든 아니든간에 그냥 파일이름만 인자값으로 넣었을때!
System.out.println(file1.exists()); // true file1과 같은이름의 폴더 혹은 파일이 존재하는가?
System.out.println(file1.isDirectory()); // false file1과 같은이름의 폴더가 존재하는가?
System.out.println(file1.length()); // 파일의 크기를 바이트 단위로 반환해줌
//파일 객체를 통한 폴더생성
File dir1 = new File("C:\\Main\\Java\\Day9\\Test\\"); //폴더만들기도 File클래스 사용
dir1.mkdir(); //폴더 주소만 넣었을때 사용할수있는 메서드 make directory 생성메소드 꼭 사용해야함
//파일 객체를 통한 특정폴더에 특정파일 생성
File file2 = new File(dir1,"input2.txt");// (경로,파일이름)
try {
file2.createNewFile(); //이 메소드를 꼭 사용해야 비로소 파일이 생성된다 & 예외처리까지해줘야햄
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(file2.getPath()); // 상대경로
System.out.println(file2.getAbsolutePath()); //절대경로
}
}
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class File2 {
public static void main(String[] args) {
byte[] arr = new byte[40]; //20byte
//FileInputStream만 사용해서 파일을읽어와 byte배열에 때려박는 예제
//fis fos는 바이트 단위 작은빨떄느낌
try {
FileInputStream fis = new FileInputStream("input3.txt"); // 파일을 인자값으로 넣어주면
System.out.println((char)fis.read()); //FileInputStream에 read()는 한글자 읽어서반환 후 커서가 다음칸으로 옮겨짐
//바이트단위로 읽어오기때문에 숫자가 들어옴 그래서 ch1ar로 변경해줘야함 // 한글자만 받을때
// read() 의 반환형은 int 이다!!!!!!!!!!!
fis.read(arr); ///바이트단위로 받아와서 가끔 터미널 문제로 출력이 이상하게 나올때도있음
///read의 또다른기능! read안에 배열, 숫자1, 숫자2 인자 넣어주면 숫자1부터 숫자2까지 읽은걸 배열안에 넣음
//빨대개념으로 설명하자만 fis는 이미 input3에 꼽힌 빨대 그래서 입구=====input3.txt
//입구만 arr로 바꾸는거야 그래서 arr에 input3.txt가 쭈욱~ 들어간다 fis는 빨대꼽는느낌
//read가 읽는건데 읽는다는게 눈으로 글을 딱 보면 글들이 눈쪽으로 쭈욱 들어와서 머리속으로 들어가잖아 이런느낌 쭈욱 들어오는느낌
//빨아땅기는느낌
for(byte b: arr){
System.out.print((char)b); // + 뒤늦게 원인을 찾았는데 " " 이거넣으면 터미널에서 좀 이상하게 받아들임
}
} catch(FileNotFoundException e){
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
//input은 외부에있는 것을 자바로 끌어들이는것
}
}
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
public class File3 {
public static void main(String[] args) {
String input = "input3.txt";
String output = "output1.txt";
//파일 받아와 읽어서 새로운파일을 만들어 내보는 예제다
try {
FileInputStream fis = new FileInputStream(input); //읽어올 파일을 인자값으로 넣고 fis에 넣자 ======O 빨대 꽂았어
FileOutputStream fos = new FileOutputStream(output); // 내보낼 파일명을 적어준다 output
int b;
while((b = fis.read()) != -1){ //read에 인자없으면 한글자만 읽고 커서 다음으로 넘기는데 반복문이니 읽고 다음꺼 읽고 다음꺼
//read()는 끝에 다달으면 -1 반환한다
fos.write(b); //FileOutputStream은 파일 작성시 write을 이용하여 작성
//넣을땐 (char)로 변환 안해도 바로 문자형으로 변환되어서 작성됨
System.out.print((char)b); //System.out.println으로 작성시에만 char로 변환 시켜줘서 출력하면됨
};
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
}
}
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class File4 {
public static void main(String[] args) {
//업그레이드된 큰빨때느낌, 바이트단위에서 문자열단위로 업그레이드됨
//FileReader 사용해서 읽고 콘솔에 출력, filereader의 read에 배열 넣을시 char타입 만 입력가능 //대형흡수빨대같은느낌
char[] arr = new char[50]; //file reader부터는 char써야함
try{
FileReader fr = new FileReader("input1.txt"); //filereader이라는 놈이 등장 얘도일단 파일명 넘겨줍니다
System.out.println((char)fr.read()); //얘도 똑같이 read메서드가있고, 똑같이 한글자만 입력받고 커서 옮김,int 값으로 반환하기에 char로 형변환시켜줌
//중요한거 FileReader에 read는 String타입 또는 char배열 또는 File타입만 취급함
fr.read(arr); //fr로 읽어들인 값들을 arr배열에 다 집어넣는데, 무조건 char형태의 배열에만 넣을수있음
for(char c:arr){
System.out.print(c);
}
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
}
import java.io.FileWriter;
import java.io.IOException;
public class FIle5 {
public static void main(String[] args) {
//FileWriter객체를 이용해서 바로 파일에다가 write가능! fos필요없네 //대형뱉는빨대느낌
String str = "내일만 공부하면 4일쉰다";
char a = 'd';
byte b = 'd';
try{
FileWriter fw = new FileWriter("output2.txt"); //생성할 파일명을 적어준다
fw.write(str.charAt(0)); //write에 문자열을쓰든 char을 쓰든 byte 을 쓰든 넘기면 다써짐
fw.write("\n");
fw.write(str);
fw.write("\n");
fw.write(str.charAt(0));
fw.write("\t");
fw.write("일만 공부하면 4일쉰다!!!");
fw.write(a);
fw.write(b);
fw.close();// 대신 !!!!!! 꼭 닫아줘야함!!!!!!!!!!!
}catch(IOException e){
e.printStackTrace();
}
}
}
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class File6 {
public static void main(String[] args) {
//scanner를 사용한 파일 입력받아 콘솔에 출력해보기//scanner는 빨대를 이용한다
String file = "input1.txt";
try{
// FileInputStream fis = new FileInputStream(file);
// Scanner sc = new Scanner(fis); //지금까지는 read를 이용해서 한글자씩받았는데
// 이제부터는 라인별로 받을수있는 스캐너를 써볼건데
//Scanner sc = new Scanner(System.in)
//이런식으로 콘솔(시스템)내에서 입력을 받아서 출력해주는 거였는데
//콘솔(시스템)대신 특정파일에서 스캔을 받고싶고
//파일을 자바는 바로 쓰질 못하니 stream을 통해서 파일을 읽어들일수있으므로
//Scanner생성할때 fis객체를 참조변수 써서해도되고 new써서 바로 넣어도 되고!
Scanner sc = new Scanner(new FileInputStream(file));
while(sc.hasNextLine()){ //hasNextLine()은 줄에 머 있나요? 있음 true 없음 false
String str = sc.nextLine();
System.out.println(str);
}
}catch (FileNotFoundException e){
e.printStackTrace();
}
}
}
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
public class File7 {
public static void main(String[] args) {
//PrintWirter을 이용해서 파일에 문자열을 쉽게 작성! 꼭 닫아줘야함//빨대이용
String file = "output3.txt";
String[] arr = {"김사과","오렌지","반하나","이메론"};
//FileOutputStream fos = null;
try {
PrintWriter pw = new PrintWriter(new FileOutputStream(file)); //써주는객체 =====(빨대같은역할이 fileoutputstream) 실제파일(file)
for(int i=0;i<arr.length; i++){
System.out.print(arr[i] + " ");
//pw.println(arr[i]
pw.print(arr[i] + " "); //write 대신 print를 이용함 그래서 printwriter
pw.print("ddd");
}
pw.close(); //꼭 닫아줘야함
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
public class File8 {
public static void main(String[] args) {
ArrayList<Product1> list = new ArrayList<>();
list.add(new Product1("아이폰14",1400000,"애플"));
list.add(new Product1("에어팟",400000,"애플"));
list.add(new Product1("애플워치",450000,"애플"));
list.add(new Product1("갤럭시22",990000,"삼성"));
list.add(new Product1("갤럭시버즈",250000,"삼성"));
for(Product1 a : list){
System.out.println(a);
}
String file = "print.txt";
try{
PrintWriter pw = new PrintWriter(new FileOutputStream(file));
for(Product1 p: list){
pw.println(p);
}
pw.close();
}catch(FileNotFoundException e){
e.printStackTrace();
}
}
}
public class Product1 {
private String pname;
private int price;
private String company;
public Product1(String pname, int price, String company) {
this.pname = pname;
this.price = price;
this.company = company;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(pname).append(", ").append(price).append(",").append(company);
return sb.toString();
}
}
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class assignment {
public static void main(String[] args) {
ArrayList<Product> list = new ArrayList<>();
String file = "product.txt";
try{
Scanner sc = new Scanner(new FileInputStream(file));
while(sc.hasNextLine()){
String str = sc.nextLine();
String[] sarr = str.split(",");
Product product = new Product(sarr[0],Integer.parseInt(sarr[1]),sarr[2]);
list.add(product);
}
}catch (FileNotFoundException e){
e.printStackTrace();
}
for(int i=0;i<list.size();i++) {
System.out.println(list.get(i)); //오버라이딩 안해주면 기본 toString은 주소값출력됨
}
}
}
public class Product {
private String name;
private int price;
private String company;
public Product(String name, int price, String company) {
this.name = name;
this.price = price;
this.company = company;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
@Override
public String toString() {
return getName() + " " + getPrice() + " " + getCompany();
}
}
반응형
'서버&백엔드 > 🔥 JAVA' 카테고리의 다른 글
학원1개월차 시험 (0) | 2022.10.17 |
---|---|
Java | Thread,동기화,join,wait,notify,notifyall (0) | 2022.10.07 |
Java | 제네릭, 컬렉션프레임워크 (1) | 2022.10.05 |
Java | 래퍼클래스,static,추상클래스,인터페이스,패키지 (1) | 2022.10.04 |
Java | 배열,Object,상속,캐스팅,instanceof (0) | 2022.10.01 |