입출력 (I/O)

조윤후·2021년 7월 19일
0

I/O 란

입력(input)과 출력(Output)을 뜻한다. 컴퓨터가 입력하는것은 Input 이며, 컴퓨터가 출력하는것을 Output이라고 한다. 대표적으로 system.out.println(); 구문이 output이다.

InputStream 사용법

  • InputStream (추상)클래스를 이용해서 객체를 만든다. 또는 다른 클래스의 메소드에서 반환(리턴)되는 타입 객체를 얻는다
  • read()메서드를 이용해서 데이터를 읽으면 된다.
  • read(), read(byte[]) 두개의 메소드를 이용할수 있다.

read()메서드 사용법

package sutdy.java.ex20_InputOutput;

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

public class InputClass {

	public static void main(String[] args) {
		
		try {
			InputStream is = new FileInputStream("D:\\jain.txt");
			while (true) {
				int i = is.read();
				System.out.println("데이터 : " + i );
				if (i == -1) {
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

OutputStream 사용법

  • OutputStream 클래스를 이용해서 객체를 만든다. 또 다른 클래스의 메소드에서 반환(리턴)되는 타입 객체를 얻는다.
  • write()메서드를 이용해서 데이터를 읽으면 된다.
  • write(),wrtie(byte[]), write(byte[], int, int ) 세개의 메서드를 이용할수 있다.
  • write(byte[], int, int )는 데이터를 원하는 위치에 원하는 숫자만큼 쓸수 있다.
package sutdy.java.ex20_InputOutput;

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

public class OutputStreamClass {

	public static void main(String[] args) {
		
		try {
			OutputStream os = new FileOutputStream("D:\\jaOut.txt");
			String str = "너무 어렵다";
			byte[] bs = str.getBytes();
			os.write(bs);
			
		} catch (Exception e) {
			e.getStackTrace();
		}
	}
}
package sutdy.java.ex20_InputOutput;

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

public class OutputStreamClass {

	public static void main(String[] args) {
		
		OutputStream os = null;
		
		try {
			os = new FileOutputStream("D:\\jaOut.txt");
			String str = "너무 어렵다";
			byte[] bs = str.getBytes();
			os.write(bs);
			
		} catch (Exception e) {
			e.getStackTrace();
		} finally {
			try {
				if (os != null) {
					os.close(); //연결을 끊는 부분
				}
			}catch(Exception e) {
				
			}
		}
	}
}
profile
공부하며 예제풀이 정리

0개의 댓글