Day 42 (23.02.23)

Jane·2023년 2월 23일
0

IT 수업 정리

목록 보기
51/124

1. I/O Stream

1-1. 기초적인 OutputStream / InputStream

  • 파일의 입력과 출력을 진행할 때는 throws IOException를 꼭 명시할 것!!
  • 경로를 따로 지정해주지 않으면, 해당 프로젝트 폴더에 생성해준다.

OutputStreamPractice.java

  • OutputStream으로 "data.dat"이라는 객체를 만든다. (파일 생성)
  • write()로 객체에 7을 넣는다.
  • Stream을 닫는다.
import java.io.*;

public class OutputStreamPractice {

	public static void main(String[] args) throws IOException {
		
		OutputStream out = new FileOutputStream("data.dat");
		out.write(7);
		out.close();
	}

}

InputStreamPractice.java

  • InputStream으로 "data.dat" 객체를 만든다.
  • dat으로 InputStream 객체를 읽어온다. (내용의 자료형에 맞게)
  • 다 읽어왔으면 Stream을 닫는다.
  • 변수에 담겨 있는 객체를 출력한다.
import java.io.*;

public class InputStreamPractice {

	public static void main(String[] args) throws IOException {
		
		InputStream in = new FileInputStream("data.dat");
		int dat = in.read();
		in.close();
		System.out.println(dat);
	}

}
  • read()는 기본적으로 1byte(8bit)씩 읽는다.

FileInputStream 클래스 >> FileInputStream(String name)

public FileInputStream(String name) throws FileNotFoundException {
	this(name != null ? new File(name) : null);
}

1-2. try ~ finally 추가

OutputStreamPractice.java

import java.io.*;

public class OutputStreamPractice {

	public static void main(String[] args) throws IOException {

		OutputStream out = null;

		try {
			out = new FileOutputStream("data.dat");
			out.write(7);

		} finally {
			if (out != null) {
				out.close();
			}
		}
	}

}

InputStreamPractice.java

import java.io.*;

public class InputStreamPractice {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		InputStream in = null;
		try {
			in = new FileInputStream("data.dat");
			int dat = in.read();

			System.out.println(dat);
		} finally {
			if (in != null) {
				in.close();
			}
		}
	}

}

1-3. try-with-resource로 변경하기

  • [스트림객체].close() 를 넣지 않아도 되는 형식이다.

OutputStreamPractice.java

import java.io.*;

public class OutputStreamPractice {

	public static void main(String[] args) throws IOException {

		try (OutputStream out = new FileOutputStream("data.dat")) {

			out.write(7);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

InputStreamPractice.java

import java.io.*;

public class InputStreamPractice {

	public static void main(String[] args) throws IOException {

		try (InputStream in = new FileInputStream("data.dat")) {

			int dat = in.read();
			System.out.println(dat);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

2. 파일 복사하기

  • IOException : 입출력에 관한 예외처리
  • FileNotFoundException : 해당하는 파일을 찾을 수 없을 때의 예외처리

2-1. 파일 복사 기본 코드

import java.io.*;
import java.util.*;

public class JavaTest {
	public static void main(String[] args) throws FileNotFoundException, IOException {
		Scanner sc = new Scanner(System.in);
		System.out.print("대상 파일 : ");
		String src = sc.nextLine();
		System.out.print("사본 이름 : ");
		String dst = sc.nextLine();

		try (InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst)) {
			int data;
			while (true) {
				data = in.read();
                // iterator가 data를 읽어나간다. (iterator의 next(), hasNext())
				if (data == -1) { // 파일의 끝 : Java에서는 -1로 return한다.
					break;
				}
				out.write(data);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
  • 패키지 안의 프로젝트에 원하는 데이터파일을 넣고 복사할 수 있다.
  • 절대 경로 형태로도 가능하다. (C:\Users\USER ... )
  • 1바이트씩 읽는 형태이므로, 시간이 걸릴지도...

2-2. 1KB씩 읽는 코드 (보다 빨라진 코드)

import java.io.*;
import java.util.*;

public class JavaTest {
	public static void main(String[] args) throws FileNotFoundException, IOException {
		Scanner sc = new Scanner(System.in);
		System.out.print("대상 파일 : ");
		String src = sc.nextLine();
		System.out.print("사본 이름 : ");
		String dst = sc.nextLine();

		try (InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst)) {
			
			byte buf[] = new byte[1024];
			int len;
			while (true) {
				len = in.read(buf);
				if(len == -1) {break;}
				out.write(buf, 0, len);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
  • byte[ ] 형식의 버퍼를 만들어서 1024 byte(1kb)씩 읽어들인다.

3. 필터 스트림 (보조 스트림)

3-1. 필터 스트림 기본 코드

  • 다양한 형태의 자료형(기본적으로 제공하는 data type)을 write, read 할 수 있다.

OutputStreamPractice.java

import java.io.*;

public class OutputStreamPractice {

	public static void main(String[] args) throws IOException {

		try (DataOutputStream out = new DataOutputStream(new FileOutputStream("data.dat"))) {
			out.writeInt(370);
			out.writeDouble(3.14);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

InputStreamPractice.java

import java.io.*;

public class InputStreamPractice {

	public static void main(String[] args) throws IOException {

		try (DataInputStream in = new DataInputStream(new FileInputStream("data.dat"))) {
			int numInt = in.readInt();
			double numDouble = in.readDouble();
			System.out.println(numInt);
			System.out.println(numDouble);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

3-2. 버퍼링 기능이 들어간 필터 스트림

import java.io.*;
import java.util.*;

class JavaPractice {

	public static void main(String[] args) throws IOException {
		Scanner sc = new Scanner(System.in);
		System.out.print("대상 파일 : ");
		String src = sc.nextLine();
		System.out.print("사본 이름 : ");
		String dst = sc.nextLine();

		try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(src));
				BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dst))) {
			int data;
			while (true) {
				data = in.read();
				if (data == -1) {
					break;
				}
				out.write(data);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}

4. FileWriter와 FileReader 연습

  • 바이트 스트림 - .class, .exe / 문자 스트림 - .java, .txt

4-1. FileWriter 객체로 문자 스트림 기반 문자 저장하기

  • 코드 작성 후 파일 확인
import java.io.*;
import java.util.*;

public class JavaTest {
	public static void main(String[] args) throws FileNotFoundException, IOException {
	
		try (Writer out = new FileWriter("data.txt")) {
			out.write('A');
			out.write('뭐');
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

4-2. FileReader 객체로 data.txt를 콘솔에 출력하기

import java.io.*;
import java.util.*;

public class JavaTest {
	public static void main(String[] args) throws FileNotFoundException, IOException {

		try (Reader in = new FileReader("data.txt")) {
			int ch;

			while (true) {
				ch = in.read();
				if (ch == -1)
					break;
				System.out.print((char) ch);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
profile
velog, GitHub, Notion 등에 작업물을 정리하고 있습니다.

0개의 댓글