아무거나

입출력(I/O) 본문

Java/Java

입출력(I/O)

전봉근 2019. 8. 16. 23:44
반응형

[입출력(I/O)]

I/O란 입력(input)과 출력(Output)을 뜻합니다. 컴퓨터한테 입력하는 것은 input이며, 컴퓨터가 어떤 것을 출력하는 것을 output이라고 합니다.

input : 파일 데이터를 읽는다, 키보드의 데이터를 읽는다, 네트워크상의 데이터를 읽는다.

output : 파일에 데이터를 쓴다, 모니터에 데이터를 쓴다(출력), 네트워크상에 데이터를 쓴다(전송)

 

[InputStream, Reader & OutputStream, Writer]

# InputStream, OutputStream : 1byte 단위 (실제로 많이 쓰임)

-> 이미지, 동영상등의 데이터에 주로 사용

# Reader, Writer : 2byte 단위

-> 문자열에 주로 사용

 

1. InputStream

- InputStream (추상)클래스를 이용해서 객체를 만든다. 또는 다른 클래스의 메소드에서 반환(리턴)되는 타입 객체를 얻는다.

- read()메소드를 이용해서 데이터를 읽으면 된다.

- read(), read(byte[]) 두개의 메소드를 이용할 수 있다.

 

-> read() : 1byte씩 읽는다. 속도가 느리다.

InputStream 객체 -> read(byte[]) : Byte[] 만큼씩 읽는다. 속도가 빠르다. -> 배열의 크기만큼 한번에 데이터를 이동하므로 속도가 빠름

ex)

InputStream is = new FileInputStream("C:\\java\\workspace\\bong.txt");

try {
    // 반드시 try ~ catch문이나 throws exception 을 사용한다. 안하면 I/O와 관련된 프로그램에선 에러난다.
    while (true) {
        int i = is.read();
        System.out.println("데이터 : " + i);
        if(i == -1) break; // 더 이상 읽을게 없을때 break; 로 빠져나간다.
    }
} catch (Exception e) {
	System.out.println(e.getMessage());
}

 

ex)

import java.io.FileInputStream;
import java.io.InputStream;

public class mainClass {
    public static void main(String[] args) {
        try {
            // 데이터를 읽어온다.
            InputStream is = new FileInputStream("C:\\bong.txt"); // 특수기호가 있으므로 \을 한번더 써준다.
            while (true) {
                int i = is.read();
                System.out.println("데이터 :" + i);
                if(i == -1) break; // 더 이상 읽을게 없으면 -1을 반환해주므로 -1일때 while문을 빠져 나간다.
            }
        } catch (Exception e) {
        	System.out.println(e.getMessage());
        }
    }
}

 

* 결과

데이터 :191

데이터 :192

데이터 :180

데이터 :195

......

......

 

 

2. OutputStream 사용법

- OutputStream 클래스를 이용해서 객체를 만든다. 또는 다른 클래스의 메소드에서 반환(리턴)되는 타입 객체를 얻는다.

- write() 메소드를 이용해서 데이터를 읽으면 된다.

- write(), write(byte[]), write(byte[], int, int) 세개의 메소드를 이용할 수 있다.

# write() : 1byte씩 쓰는거

# write(byte[]) : 배열의 크기만큼 쓰는거

# write(byte[], int, int) : 첫번쨰 매개변수인 배열의 크기만큼 두번째 매개변수 부터 세번째 매개변수 까지 자리를 지정

-> 데이터를 원하는 위치에서 원하는 숫자만큼 쓸 수 있다.

ex) write(4, 0, 1) : 배열의 크기가 4만큼 쓴것중에 0에서 1까지만 써라

 

ex)

import java.io.FileOutputStream;
import java.io.OutputStream;

public class mainClass {
    public static void main(String[] args) {
        try {
            OutputStream os = new FileOutputStream("C:\\bong.txt");
            String str = "오늘 날씨는 아주 좋습니다.";
            byte[] bs = str.getBytes(); // str문자열 값에서 글자 하나하나의 모든 byte를 배열로 반환해주는 getBytes 메서드가 있다.
            os.write(bs); // write할때는 byte단위로 써야하므로 위에서 변경해준것이다.
        } catch (Exception e) {
        	System.out.println(e.getMessage());
        }
    }
}

 

 

3. 예외 처리와 무조건 close() 실행

- I/O를 하면서 반듯이 해야 하는 예외처리가 있습니다. IOException입니다.

- I/O작업 마지막은 close()로 외부연결을 끊어야 한다.

ex)

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class mainClass {
    public static void main(String[] args) {
        OutputStream os = null;


        try {
            os = new FileOutputStream("C:\\bong.txt");
            String str = "오늘 날씨는 아주 좋습니다.";
            byte[] bs = str.getBytes(); // str문자열 값에서 글자 하나하나의 모든 byte를 배열로 반환해주는 getBytes 메서드가 있다.
            os.write(bs); // write할때는 byte단위로 써야하므로 위에서 변경해준것이다.
        } catch (Exception e) {
        	System.out.println(e.getMessage());
        } finally {
            try {
                if(os != null) os.close();
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }
    }
}

 

 

4. 읽고, 쓰기를 동시에 -> 파일복사

- 파일을 읽고, 다른 파일에 쓰고, 결국은 파일 복사 입니다.

- 작업순서 : InputStream, OutputStream 준비 -> is로 읽어들인 데이터를 os으로 씀 -> 외부연결 close()함

 

ex)

import java.io.*;

public class mainClass {
    public static void main(String[] args) {
        InputStream is = null;
        OutputStream os = null;


        try {
            is = new FileInputStream("D:\\etcutils\\bong.txt");
            os = new FileOutputStream("D:\\etcutils\\bong_copy.txt");

            byte[] bs = new byte[5];

            while (true) {
                int count = is.read(bs);
                if(count == -1) {
                    break;
                }

                os.write(bs, 0, count);
            }
        } catch (Exception e) {
        	System.out.println(e.getMessage());
        } finally {
            if(is != null) {
            try {
            	is.close();
            } catch (Exception e2) {
            	System.out.println(e2.getMessage());
            }
        }


        if(os != null) {
            try {
            	os.close();
            } catch (Exception e3) {
            	System.out.println(e3.getMessage());
            }
        }
    }
}

 

 

5. DataInputStream, DataOutputStream -> 문자열 읽고, 쓰기

- byte단위로 문자열을 처리하는 InputStream, OutputStream 보다 편리하게 고안된 클래스 입니다.

 

ex)

import java.io.*;

public class mainClass {
    public static void main(String[] args) {
        InputStream is = null;
        DataInputStream dis = null;


        OutputStream os = null;
        DataOutputStream dos = null;

        try {
            is = new FileInputStream("D:\\etcutils\\bong2.txt");
            dis = new DataInputStream(is);
            String str = dis.readUTF(); // readUTF을 활용하면 데이터를 한번에 얻어올 수 있다.(byte수나 배열수도 읽어오지 않음)


            os = new FileOutputStream("D:\\etcutils\\bong2_copy.txt");
            dos = new DataOutputStream(os);
            dos.writeUTF(str); // 이것또한 읽지않고 바로 전체를 카피할 수 있다.
        } catch (Exception e) {

        } finally {
            if(dos != null) {
                try {
                    dos.close();
                } catch (Exception e2) {
                }
            }

            if(os != null) {
            try {
            	os.close();
        	} catch (Exception e2) {
        	}
        }
        }
    }
}
반응형

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

JAVA 그래픽  (0) 2019.08.16
스레드(Thread)  (0) 2019.08.16
JAVA Collections  (0) 2019.08.16
예외처리  (0) 2019.08.16
StringTokenizer 클래스  (0) 2019.08.16
Comments