JAVA/강의

JAVA 15일차 강의 -파일 입출력

record2080 2025. 3. 4. 00:16

▶ 형변환의 2가지

- 묵시적 : double d=3;

- 강제 : int i=3.14;

             int i=(int) 3.14 >> 3 

억지로 형변환시 예외가 발생하는 경우가 있다

그럴 경우 try-catch문 사용해서 예외처리가 필요


[파일 입출력]

입력 : 컴퓨터에 저장되어있던 파일의 내용을 코드로 불러오기 (개발자입장)

>> R(read) 읽기모드

I.O : 즉 , 시스템이랑 소통

io를 쓸 때는 반드시 try-catch문을 써야함

외부동작으로 인해 오류가 발생할 수 있기 때문이다

 

출력 : 코드의 내용을 컴퓨터로 내보내기(컴퓨터에 저장시키기)

>>W(writing) 쓰기모드

 

참고) 띄어쓰기 : 제어문자 이스케이프백슬러쉬   "\n"

public class Practice {
	public static void main(String[] args) {
		
		String path="D\\JANG\\resource\\";
		String fileName="result.txt";
		String msg="안녕하세요\n:D";
		
		FileWriter fw;
		try {
			 fw=new FileWriter (fileName);
			 fw.write(msg);
		} catch (IOException e) {
			
			e.printStackTrace();
		}
		finally {   //로그확인
			System.out.println("로그 : 파일쓰기가 완료되었습니다.");
		}
	}
}

fileWriter fw=null; //객체이기 떄문에 null;인 것을 기억!!

EOF=End Of File =null

파일끝에서 EOF가 숨겨져 있고 null이 있는 이유

 

스캐너랑 랜덤도 객체  new를 하니깐
close를 쓰면 메모리관리에 효율
Writer은 close를 반드시 써야 함(시스템이랑 소통하니깐)

 

<텍스트>

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

public class Practice {
	public static void main(String[] args) {
		String path = "D:\\JANG\\resource\\";
		String fileName = "result.txt";
		
		FileReader fr;
		try {
			fr = new FileReader(path+fileName);
            // 파일을 읽기 위한 FileReader 객체 생성
			BufferedReader br = new BufferedReader(fr);
            // 파일을 한 줄씩 읽기 위한 BufferedReader 객체 생성
			
			while(true) {
				String msg=br.readLine();
				if(msg == null) {
					break;
				}
				System.out.println(msg);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
            //버퍼공간을 열어주는 코드
		} catch (IOException e) {
			e.printStackTrace();
		}		
	}
}

 

FileReader fr=new FileReader(path+fileName);//파일읽어주기
BufferedReader br=new BufferedReader(fr) //버퍼리더를 통해 한 줄씩 읽어주면서
=>BufferedReader br=new BufferedReader(new FileReader(path+fileName));

 


참고 ) 파일 입출력으로 담당했던 일은?? 도어락 (행렬정보)

 

<이미지>

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

public class Practice {
	public static void main(String[] args) {
		// 1. 원본 이미지를 코드로 불러오기
		// 2. 복사 이미지를 특정 경로에 작성하기
		String img = "D:\\JANG\\resource\\test.png";
		String dest = "D:\\JANG\\resource\\test - 복사본.png"; 
		
		FileOutputStream fw=null;
		try {
			FileInputStream fr = new FileInputStream(img);
			fw = new FileOutputStream(dest);
			
			while(true) {
				int character=fr.read();
				if(character == -1) {
					break;
				}
				fw.write(character);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			System.out.println("로그 : 이미지 복붙 완료");
		}
	}
}

 

dest: 파일이 도착하는 곳

이미지는 코드값이 있어서 읽어들일 수 있다

int character=fr.read();
왜 인트일까? 자바에서 제공하기 때문에

 

int 에서는 null을 쓸 수 없음
EOF의 값은 -1

 

▶잠깐만!!

fileOutputStream fw=null; (파일에 데이터를 쓰기 위한 스트림)

fw는fileoutputstream의 객체의 참조변수

처음에는 null로 초기화되고, 실제로 dest가 실행되면서 파일에 데이터를 쓸 수 있는 스트림객체가 생성

EOF=-1 이란

파일에서 읽을 수 있는 데이터가 더 이상 없다는 신호