ddoddii / Computer-Science-Study

🌵 지적 개발자를 위한 넓고 깊은 컴퓨터과학 지식
16 stars 5 forks source link

[java] 입출력과 스트림 #24

Open ddoddii opened 1 month ago

ddoddii commented 1 month ago

데이터 타입에 따른 스트림의 분류

입출력 스트림

스트림의 종류

바이트 스트림(Byte Stream)

InputStream 클래스

// 입력 스트림으로부터 한 바이트의 데이터를 읽음
int read() throws IOException
// 입력 스트림으로부터 데이터를 읽어서 주어진 바이트 배열 b를 채움 
int read(byte[] b) throws IOException
// 입력 스트림으로부터 주어진 바이트 배열b의 특정 오프셋off부터 최대 len 길이만큼 바이트를 읽음
int read(byte[] b, int off, int len) throws IOException
// 입력 스트림을 닫고 모든 시스템 자원을 해제 
void close() throws IOException

OutputStream 클래스

void write(int b)  throws IOException
void write(byte[] b) throws IOException
void write(byte[] b, int off, int len) throws IOException
public void flush()
public void close()

보조 스트림

객체 직렬화(Serialization) 가능 클래스 만들기

ddoddii commented 1 month ago
import java.io.*;

public class FilterStreamTest {
    public static void main(String[] args) {
        method1();
        method2();
        method3();
    }

    private static void method1() {
        try(FileReader reader = new FileReader("big_input.txt");
            FileWriter writer = new FileWriter("big_output.txt");
        ){
            long start = System.nanoTime();
            int c;
            while ((c = reader.read()) != -1) {
                writer.write(c);
            }
            long end = System.nanoTime();
            System.out.println(end - start);
        } catch(IOException e) {
            e.printStackTrace();
        }
    }

    private static void method2() {
        try(BufferedReader reader = new BufferedReader(new FileReader("big_input.txt"));
            BufferedWriter writer = new BufferedWriter (new FileWriter("big_output_method2.txt"));
        ){
            long start = System.nanoTime();
            String line; // Buffered reader 는 line 단위로 입력
            while((line = reader.readLine()) != null) {
                writer.write(line);
                writer.newLine();
            }
            long end = System.nanoTime();
            System.out.println(end - start);
        } catch(IOException e) {
            e.printStackTrace();
        }
    }

    private static void method3() {
        try(FileInputStream fis = new FileInputStream("big_input.txt");
            FileOutputStream fos = new FileOutputStream("big_output_method3.txt");
        ) {
            long start = System.nanoTime();
            int b;
            // 버퍼 이용해서 read()
            byte[] buffer = new byte[8192];
            while ((b = fis.read(buffer)) != -1) { // 입력스트림으로부터 버퍼에 바이트를 채우고, 채운 바이트의 수 반환
                fos.write(buffer,0,b);
            }
            long end = System.nanoTime();
            System.out.println(end - start);
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
}