본문 바로가기
Programming/Java

[Java] IO(입출력)

by AI_Wooah 2022. 3. 7.

입출력

Input과 Output의 약자로, 컴퓨터 내부 또는 외부 장치와 프로그램 간의 데이터를 주고 받는 것을 말한다.

장치와 입출력을 위해서는 하드웨어 장치에 직접 접근이 필요하고, 다양한 매체에 존재하는 데이터들을 사용하기 위해 입출력 데이터를 처리할 공통적인 방법으로 스트림을 이용한다.

데이터를 바이트 단위나 문자단위로 끊어서 전송해야 한다.

모든 파일은 0과 1로 되어 있다

데이터가 고속으로 지나가는 잔상(통로)을 스트림이라고 한다.

프로그램이 파일로부터 데이터를 읽어들이려면 읽어들이기 위해서 통로를 접해야 한다. 받아서 모아서 해석한다.

1바이트씩 끊어서 전송해주는 것을 파일이 끝날 때 까지 모은다.

통로는 단방향이다. 입력통로와 출력통로가 서로 다르다.

문자 단위로 읽어들이냐 바이트 단위로 읽어들이냐에 따라 4가지로 나뉜다.

프로그램 외부에 존재하는 자원(파일, 키보드, 모니터 등)을 가져올 때의 속도가 성능을 측정하는 기준이다.

어떤 통로를 이용해서 데이터를 읽어들일건지 잘 생각하고 선택해야 한다.

읽어들이고 처리해서 내보내려면 두 개의 통로가 필요하다.

읽어들이는 것을 인풋이라고 하고 내보내는 것을 아웃풋이라고 한다.

스트림 계열(바이트단위로 읽거나 내보냄)이냐 리더(문자 단위로 읽어들임) Writer계열(문자 단위로 내보냄)이냐가 중요하다.

package com.kh.io.fileTest;

import java.io.File;
import java.io.IOException;

public class TestFile {

	public static void main(String[] args) {
		//file클래스 메소드
		//파일이 없어도 파일 객체를 생성할 수 있다.
		File file = new File("person.txt"); //괄호 안에 문자열 경로 적어줌
		System.out.println("파일명 : " + file.getName());
		System.out.println("파일용량: " + file.length());
		System.out.println("파일경로: " + file.getAbsolutePath()); //최상위 위치부터 불러오는 절대경로
		System.out.println("파일경로: " + file.getPath());
		
//		try {
////			boolean isCreated = file.createNewFile();
////			System.out.println("isCreated : " + isCreated);
//			
//			
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//		boolean isDeleted = file.delete();
//		System.out.println("isDeleted : " + isDeleted);
	}

}
package com.kh.io.part01_byteStream.model.dao;

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

public class TestByteStream {
	
	public void fileOpen() {
		//파일로부터 byte 단위로 데이터를 읽어올 수 있는 스트림
		FileInputStream fin = null;
		
		try {
			fin = new FileInputStream("sample.dat"); //실제로 없는 파일이기 때문에 트라이캐치 입ㅇ혀줘야 함.
//			int fileSize = (int) new File("sample.dat").length();
//			
//			byte[] bar = new byte[fileSize];
//			
//			fin.read(bar);
//			
//			for(int i = 0; i < bar.length; i++) {
////				System.out.println(bar[i] + " ");
//				System.out.println((char) bar[i] + " ");
			int value;
			while((value = fin.read()) != -1) {
				System.out.println((char) value + " ");
			
				
			}
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if(fin != null) {
					fin.close();
				}
				fin.close();
			} catch(IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void fileSave() {
		FileOutputStream fout = null;
		
		try {
			//대상 파일이 존재하지 않으면 자동으로 파일을 만들어준다.
			fout = new FileOutputStream("sample.dat", false);
			
			fout.write(97);
			byte[] bar = {98, 99, 100, 101, 102};
//			fout.write(bar);
			fout.write(bar, 1, 3);
			
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if(fout != null) {
					fout.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		
		
		
	}
	
}
package com.kh.io.part01_byteStream.run;

import com.kh.io.part01_byteStream.model.dao.TestByteStream;

public class Run {

	public static void main(String[] args) {
		TestByteStream tbs = new TestByteStream();
//		tbs.fileOpen();
		tbs.fileSave();

	}

}
package com.kh.io.part02_charStream.model.dao;

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

public class TestCharStream {

	public void fileSave() {
		FileWriter fw = null;
		
		try {
			fw = new FileWriter("sample.txt", true);
			
			fw.write("우리나라 대한민국");
			fw.write("sdfsdf");
			char[] carr = {'a', 'p', 'p', 'l', 'e'};
			fw.write(carr);
			
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			
			e.printStackTrace();
		} finally {
			try {
				if(fw != null) {
					fw.close();
				}
				
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		
	}
	
	public void fileOpen() {
		FileReader fr = null;
		
		try {
			fr = new FileReader("sample.txt");
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			try {
				if(fr != null) {
					fr.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
package com.kh.io.part02_charStream.run;

import com.kh.io.part02_charStream.model.dao.TestCharStream;

public class Run {

	public static void main(String[] args) {
		TestCharStream t = new TestCharStream();
//		t.fileSave();
		t.fileOpen();

	}

}
반응형

'Programming > Java' 카테고리의 다른 글

[Java] Thread  (0) 2022.03.07
[Java] GUI(Graphic User Interface)  (0) 2022.03.07
[Java] Exception(예외처리)  (0) 2022.03.07
[Java] 기본 API  (0) 2022.03.07
[Java] 다형성  (0) 2022.03.07

댓글