Java

Java, io Stream(InputStream, OutputStream)

greenyellow-s 2024. 8. 5. 21:54
객체 직렬화

 

객체는 파일이나 네트워크로 전송이 안된다.
객체는 절대 보낼 수 없고 문자열만 간다.

따라서, 객체를 byte[] 단위로 (쪼개서) 변환시켜서 전송해야 한다.

쪼갠 상태에서 받지는 않고 묶어서 받게 된다.
가는 동안만에만 쪼개져 가고 도착했을때는 다시 객체로 묶어준다.(자바에서 알아서 수행함)


-> Serializable만 선언해주면 된다.

 

io Stream

 

데이터가 흘러가는 길을 만든다.

 

Application을 중심으로 받는 쪽, 보내는 쪽이 정해진다.

 

받는 쪽 <-- 입력 -- 키보드/화면(콘솔)

보내는 쪽 --> 출력 --> 파일

 

단위

 

1. byte 단위 처리(숫자, 영문자) - byte 스트림

InputStream

OutputStream

 

byte => 8bit / 영문자 1자 => 1byte , 한글 1자 => 2byte

한글이 훨씬 많은 byte를 차지하기 때문에 한글이 깨진다.

 

2. 문자(Char - 2byte) 단위 처리( 숫자, 영문자, 한글 ) - 문자 스트림

Reader

Writer

 

한글은 깨지지 않지만 속도는 느려진다.

 

BufferOutputStream -> 버퍼로 byte 단위로 보낸다

ButterWriter -> 버퍼로 문자 단위로 보낸다

 


FileInputStream / BufferedInputStream (파일 읽기)
public static void main(String[] args) throws IOException {
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream("data.txt"));
    int data;

    //파일에서 1글자씩 읽기
    while( (data=bis.read()) != -1 ) {
        System.out.print((char)data);
    }
    System.out.println();

    bis.close();
}

 

 

FileInputStream / BufferedInputStream (파일 생성)
public static void main(String[] args) throws IOException {
    File file = new File("data.txt"); //파일 생성
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));

    int size = (int)file.length(); //파일 크기

    //파일의 크기만큼 byte[] 생성
    byte[] b = new byte[size];

    //파일안의 내용에 한번에 읽기
    bis.read(b, 0, size);

    System.out.println(new String(b)); //byte[] => String 변환

    bis.close();
}

 


FileOutputStream / DataOutputStream (파일 쓰기)
//DataOutputStream dos = new DataOutputStream(new FileOutputStream("result.txt"));

FileOutputStream fos = new FileOutputStream("result.txt");
DataOutputStream dos = new DataOutputStream(fos);

dos.writeUTF("홍길동");
dos.writeInt(25);
dos.writeDouble(185.3);

dos.close();

//파일에 들어간 순서대로 나온다.
DataInputStream dis = new DataInputStream(new FileInputStream("result.txt"));
String name = dis.readUTF();
int age = dis.readInt();
double height = dis.readDouble();

System.out.println("이름 = " + name);
System.out.println("나이 = " + age);
System.out.println("키 = " + height);

dis.close();

 

FileOutputStream / ObjectOutputStream (파일 쓰기)
public static void main(String[] args) throws IOException, ClassNotFoundException {
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("result2.txt"));// buffer로 넣고 txt로 내보낸다.

    PersonDTO dto = new PersonDTO("홀길동", 25, 185.3);

    oos.writeObject(dto);
    oos.close();

    ObjectInputStream ois = new ObjectInputStream(new FileInputStream("result2.txt"));
    //Object ob = ois.readObject(); --> object를 쓰면 최상위꺼를 가져온다.
    PersonDTO dto2 = (PersonDTO)ois.readObject(); // 자식 = (자식)부모
    // 자식은 부모의 것을 바로 가져올 수 없다. 따라서 캐스팅으로 가져온다.

    System.out.println("이름 = " + dto2.getName());
    System.out.println("나이 = " + dto2.getAge());
    System.out.println("키 = " + dto2.getHeight());
    // toString으로 해도 가능


    ois.close();
    }

'Java' 카테고리의 다른 글

Java, 함수형 프로그래밍 / 람다식  (0) 2024.08.05
Java, 스레드, 동기화처리, 싱글톤  (0) 2024.08.05
Java, 정렬(CompareTo, Compartor)  (0) 2024.08.02
Java, Iterator(반복자)  (0) 2024.07.30
Java, Collection (Set, List,Map,Queue)  (0) 2024.07.30