KakaoTalk_20220714_162048959.jpg

입력과 출력의 기준은 메모리이다.

파일 읽기 작업을 위한 클래스이다.

- 파일,네트워크,키보드 >>>>>Fileinputstream(byte)>>>메모리>>>>>>>outputstream>>>>파일

파일 읽기 과정

1)FileInputStream 객체 생성

2)읽기 작업

기본 예제

1)바이트 단위 읽기

package com.java.io03_fileinputstream;

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

public class FileInputSteam01 {

	public static void main(String[] args) {
		// 입출력 > byte 단위 입출력 > Stream> InputStream>FileInputStream(호수,빨대)> 
		//read()
		
		
		FileInputStream fis = null;
		
		try {
			
			//1.파일 입력 스트림 생성
			 fis= new FileInputStream("C:\\\\FileTest\\\\dir1\\\\test01.txt");
		
		   //2.파일 읽기
		   //1) 무한 반복 +파일 끝(-1)에서 끝남
//			while(true) {
//			int read=fis.read();  //the next byte of data, or -1 if the end of the file is reached.
//			if(read ==-1) break;
//			System.out.print((char)read); //
			
//			}	
		   //2)코드 수정
//			int read;
//			while((read=fis.read()) !=-1) {
//				System.out.print((char)read); //				
//			}
			//3)추가 수정
			 
		//	int read = 0;
			 //read() 메서드를 두번 사용했기 때문에 커서가  다음으로 이동하면 출력하지 못하게 된다.
			while((fis.read()) !=-1) { //w l o e 
				System.out.print((char)(fis.read()));//e c m t 				
			}
			
		
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		}
		
		//3.스트림 종료
		//입출력 스트림은 출력후 바로 객체를 종료해주는 것이 좋다.
			try {
				if(fis != null)  //fis 객체 생성 되어 있으면 종료한다.
				fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

	}

}

2)바이트 배열을 이용하여 읽기

package com.java.io03_fileinputstream;

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

public class FileInputStream02 {

	public static void main(String[] args) {
		// byte 단위 입출력 >Stream >InputStream>FileInputStream>read(byte[] by)

		// 1.파일 객체 생성
		FileInputStream fis = null;

		try {
			fis = new FileInputStream("C:\\\\FileTest\\\\dir2\\\\test01.txt");

			// 2.읽어 오기
			// the buffer into which the data is read. 데이터를 읽는 버퍼입니다.
			// the total number of bytes read into the buffer,
			// or -1 if there is no more data because the end of the file has been reached.
			// 버퍼로 읽혀진 총 바이트 수, 또는 파일 끝에 도달하여 더 이상 데이터가 없으면 -1입니다.

			// 버퍼를 미리 생성
			// 미리 만들어진 40바이트 짜리 배열에 글자를 저장한다.
			byte[] by = new byte[40];
			while (true) {
				int read = fis.read(by); // 버퍼로 읽혀진 총 바이트 수
				if (read == -1)
					break;
				System.out.println(read + "바이트");
			}

			// String 생성자를 통해 문자열로 변환해 준다.
			String msg = new String(by);
			System.out.println(msg);

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// 3.종료 작업
		try {
			if (fis != null)
				fis.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}// main

}

3)n-byte 단위 출력