1. 스트림
System.in → InputStream
package ex18;
import java.io.IOException;
import java.io.InputStream;
public class Buff01 {
    public static void main(String[] args) {
        InputStream in = System.in; // 키보드 -> os -> System.in 으로 1Byte씩 받을 수 있는 선
        try {
            int r = in.read(); // 키보드 입력 대기
            System.out.println(r); // 1Byte만 받기 때문에 글자 1개만 받을 수 있다
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

- 입력된 첫 번째 값만 읽는다
- 2진 데이터를 정수값으로 변환해서 읽는다
InputStreamReader
package ex18;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Buff02 {
    public static void main(String[] args) {
        InputStream in = System.in; // 키보드 -> os -> System.in 으로 1Byte씩 받을 수 있는 선
        InputStreamReader rd = new InputStreamReader(in); // 1Byte씩 받는 데이터를 char로 캐스팅한다.
        char[] buf = new char[4]; // 내가 만든 고정크기의 버퍼
        try {
            rd.read(buf); // 키보드 입력 대기
            System.out.println(buf[0]);
            System.out.println(buf[1]);
            System.out.println(buf[2]);
            System.out.println(buf[3]);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

- 지정한 버퍼의 크기 만큼만 데이터를 받는다.
- 정수를 문자로 캐스팅 해준다.
BufferedReader
package ex18;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Buff03 {
    public static void main(String[] args) {
//        InputStream in = System.in;
//        InputStreamReader rd = new InputStreamReader(in);
//        BufferedReader br = new BufferedReader(rd);
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // 자동으로 가변버퍼를 만들어 준다. char[] -> ArrayList -> String
        try {
            String line = br.readLine();
            System.out.println(line);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

- 가변 버퍼를 만들어 데이터를 읽는다.
- \n 까지의 문자를 받아 문자열로 읽는다.
BufferedWriter
package ex18;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
// 버퍼는 꽉 차야 전송됨
// 프로토콜 : "\n" <- 기호를 메시지의 종단에 포함을 시켜야 읽는 쪽에서 사용가능
// data -> writerBuffer -> flush -> readerBuffer -> data
public class Buff04 {
    public static void main(String[] args) {
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        try {
            bw.write("안녕\n");
            bw.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
- 버퍼는 꽉 차면 자동으로 흘러간다
- 꽉 차지 않고 보내려면 flush 메서드를 사용한다
- 보낸 데이터 종단에 \n이 없으면 읽을 수 없다.
- out 은 모니터 출력을 의미한다.
- out buffer를 만들어서 글자를 입력한다.
PrintWriter & Scanner
package ex18;
import java.io.PrintWriter;
import java.util.Scanner;
public class Buff05 {
    public static void main(String[] args) {
        PrintWriter out = new PrintWriter(System.out, true);
        out.println("hello world");
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        System.out.println(str);
    }
}
- BufferedWriter를 사용하기 쉽게 만들어 준 클래스
- 아직은 사용하지 말자!
2. 예제
파일 읽기(15-1)
package ex18;
import java.io.FileReader;
import java.io.IOException;
public class FileReaderEx01 {
    public static void main(String[] args) {
        try {
            FileReader fr = new FileReader("test.txt");
            int ch;
            // fr버퍼에서 내용을 읽었을때, 내용이 없으면 -1을 읽음 (그때 while 종료하면 됨)
            while ((ch = fr.read()) != -1) {
                System.out.println((char) ch);
            }
            fr.close(); // 스트림이 끝나면 반드시 닫아야한다.
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

- 한글이나 영문이 모두 2바이트 문자(유니코드)로 출력되고 있다.
- 버퍼로 데이터를 받다가 끝나면 반드시 연결을 끊어야한다.
package ex18;
import java.io.*;
public class FileReaderEx01 {
    public static void main(String[] args) {
        try {
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(new FileInputStream("test.txt"))
            );
            String line = br.readLine();
            System.out.println(line);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
- FileInputStream 클래스로 파일을 스트림 데이터로 만들어 읽는다.
파일 복사하기(15-2)
package ex18;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileReaderEx04 {
    public static void main(String[] args) {
        try  {
            FileReader in = new FileReader("test.txt");
            FileWriter out = new FileWriter("copy.txt");
            int c;
            while ((c = in.read()) != -1) {
                out.write(c);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

package ex18;
import java.io.*;
public class FileReaderEx03 {
    public static void main(String[] args) {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("test.txt")));
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("copy.txt")));
            String m = br.readLine() + "\n";
            bw.write(m);
            bw.flush();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

바이트 스트림(15-3)
이진 파일 쓰기
package ex18;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileStreamTest {
    public static void main(String[] args) {
        byte[] list = {10, 20, 30, 40, 50, 60};
        try {
            FileOutputStream out = new FileOutputStream("test.bin");
            for (byte b : list) {
                out.write(b);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
이진 파일 읽기
package ex18;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileStreamTest2 {
    public static void main(String[] args) {
        byte[] list = new byte[6];
        try {
            FileInputStream in = new FileInputStream("test.bin");
            in.read(list);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        for (byte b : list) {
            System.out.print(b + " ");
        }
    }
}
이미지 파일 복사하기
package ex18;
import java.io.*;
import java.util.Scanner;
public class ByteStreamsLab {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("원본 파일 이름을 입력하시오: ");
        String inputFileName = sc.next();
        System.out.println("복사 파일 이름을 입력하시오: ");
        String outputFileName = sc.next();
        try {
            InputStream inputStream = new FileInputStream(inputFileName);
            OutputStream outputStream = new FileOutputStream(outputFileName);
            int c;
            while ((c = inputStream.read()) != -1) {
                System.out.println(c);
                outputStream.write(c);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        System.out.println(inputFileName + "을 " + outputFileName + "으로 복사하였습니다.");
    }
}
- FileInputStream & FileOutputStream 은 오라클에서 제공하는 클래스라 close()가 이미 구현되어 있다.
중간 처리 스트림(15-4)
이진수 저장 파일 읽기
package ex18;
import java.io.*;
public class DataStreamTest {
    public static void main(String[] args) {
        DataInputStream in = null;
        DataOutputStream out = null;
        try {
            out = new DataOutputStream(new FileOutputStream("data.in"));
            out.writeInt(123);
            out.writeFloat(123.456F);
            out.close();
            in = new DataInputStream(new FileInputStream("data.in"));
            int aint = in.readInt();
            float afloat = in.readFloat();
            System.out.println(aint);
            System.out.println(afloat);
            in.close();
            out.close();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
버퍼 스트림
줄 단위 복사하기
package ex18;
import java.io.*;
public class CopyLines {
    public static void main(String[] args) {
        try {
            BufferedReader in = new BufferedReader(new FileReader("test.txt"));
            PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
            String line;
            while ((line = in.readLine()) != null) {
                out.println(line);
                out.flush();
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

Share article