본문 바로가기
Framwork/Java기초

Chapter 13. 자바 입출력

by 김엉배 2023. 10. 19.
728x90
반응형

목차

1. 스트림(stream)
2. 표준 입출력 클래스
3. 파일 입력 클래스
4. 파일 출력 클래스

 

  • 자바 입출력은 크게 표준 입력과 파일 입출력으로 나눌 수 있다.
    - 표준 입출력은 키보드로부터 입력을 받고 모니터로 출력하는 것을 말한다.
    - 파일 입출력은 파일로부터 데이터를 입력받아서 다시 파일로 출력하는 것을 말한다.

 

 

1.  스트림(stream)


- 스트림은 데이터가 다니는 길을 말한다.

- 컴퓨터와 입출력 장치 사이에 연결된 길이고 이러한 스트림에 적절한 입출력 클래스를 이용해 데이터를 읽어 들이거나 출력하게 된다.

  • 입력 스트림 클래스: 클래스명이 InputStream 또는 Reader로 끝남.
  • 출력 스트림 클래스: 클래스명이 OutputStream 또는 Writer로 끝남.
  • 바이트 단위 입출력 클래스: 클래스명이 Stream으로 끝나는 클래스.
  • 문자 단위 입출력 클래스: 클래스명이 Reader/Writer로 끝나는 클래스.
  • 보조 스트림 클래스
    - InputStreamReader, OutputStreamReader
    - BufferedInputStream, BufferedOutputStream
    - DataInputStream, DataOutputStream

 

 

2.  표준 입출력 클래스


- 표준 입력은 키보드로부터 데이터를 입력받는 것을 말한다.

 

1) Scanner 클래스

  • 표준 입력 처리에 아주 유용.
  • java.util 패키지에 있다.
  • 다양한 자료형을 읽어올 수 있는 메소드들이 있어 다앙한 데이터 입출력 처리에 유용

[생성자]

생성자 설명
Scanner(File source) 파일 객체로부터 Scanner 객체를 생성함.
Scanner(InputStream source) InputStream 객체로부터 Scanner 객처를 생성함.

 

[메소드]

메소드 설명
void close() Scanner 객체를 닫음.
String next() 문자열 데이터를 읽음.
boolean nextBoolean() boolean 데이터를 읽음.
byte nextByte() byte 데이터를 읽음.
short nextShort() short 데이터를 읽음.
int nextInt() int 데이터를 읽음.
long nextLong() long 데이터를 읽음.
float nextFloat() float 데이터를 읽음.
double nextDouble() double 데이터를 읽음.
* Scanner 클래스를 이용하면 표준 입력을 쉽게 해결할 수 있다.
import java.util.Scanner;

Scanner scin = new Scanner(System.in);
String x = scin.next();
int y = scin.nextInt();
double z = scin.nextDouble();

scin.close();

[예제]

import java.util.Scanner;

public class code208 {
  public static void main(String[] args) {
    Scanner scin = new Scanner(System.in); // System.in 키보드를 말한다.
    System.out.print("Name : ");
    String name = scin.next(); // Stirng 읽을 때
    System.out.print("Phone number : ");
    String phone = scin.next();
    System.out.print("Age : ");
    int age = scin.nextInt(); // int 읽을 때
    System.out.print("Height : ");
    float height = scin.nextFloat(); // float 읽을 때
    System.out.print("Gender : ");
    char gender = scin.next().charAt(0); // String의 첫문자

    System.out.println("Name : " + name);
    System.out.println("Phone : " + phone);
    System.out.println("Age : " + age);
    System.out.println("Height : " + height);
    System.out.println("Gender : " + gender);

    scin.close();
  }
  
}

----------------------------------------------------------------
결과
Name : Alice
Phone number : 010-1111-2222
Age : 21
Height : 160
Gender : Female
Name : Alice
Phone number : 010-1111-2222
Age : 21
Height : 160.0 
Gender : F

 

2) System 클래스

  • System 클래스를 이용해 키보드로부터 데이터를 읽어 들이는 방법

 

[필드]

in :  public static final InputStream in
out :  public static final PrintStream in
err : public static final PrintStream out

 

[System.in]

  • 필드인 in이 InputStream 타입이기 때문에 InputStream 클래스에 있는 메소드들을 사용할 수 있다.
public abstract int read() throws IOException
public int read(byte[] b) throws IOException
public int read(byte[] b, int off, int len) throws IOException

[예제]

import java.io.IOException;

public class code209 {
  public static void main(String[] args) {
    System.out.print("Enter one character : ");
    int x;
    try {
      x = System.in.read();
      System.out.println("You entered " + x);
      // read() 메소드 반환값은 int 이므로 char형으로 형 변환해야 한다.
      System.out.println("You entered " + ((char)x));
    }
    catch(IOException e) {
      e.printStackTrace();
    }
  }
}
------------------------------------------------------------------
결과
Enter one character : a
You enterd 97
You enterd a
import java.io.IOException;

public class code210 {
  public static void main(String[] args) {
    int x;
    try {
      // 읽어들일 문자가 없으면 -1 을 반환
      while((x = System.in.read()) != -1) {
        System.out.print((char)x);
      }
    }
    catch(IOException e) {
      e.printStackTrace();
    }
  }
}
----------------------------------------
결과
helow world
helow world

 

3) System.out

  • out은 PrintStream 타입이기 때문에 PrintStream 클래스의 메소드들을 사용 가능
  • write()와 print() 메소드가 있다.

[write 메소드]

메소드 설명
public abstract void write(int b) throws IOException 정수 b의 하위 8 비트를 출력함.
public abstract void write(byte[] b) throws IOException byte 배열 b의 내용을 출력함.
public abstract void write(byte[] b, int off, int len) throws IOException 배열 b의 off위치부터 len 길이만큼 출력함.

 

 

 

 

3.  파일 입력 클래스


- 파일로부터 데이터를 읽어 오는 클래스는 FileInputStream 과 FileReader 클래스가 있다.

- 파일에 데이터를 저장(출력)하는 클래스는 FileOutputStream과 FileWriter 클래스가 있다.

 

[파일 입력 클래스]

  • FileInputStream : 파일로부터 바이트 단위로 데이터를 읽어 온다.
  • FileReader : 파일로부터 문자 단위로 데이터를 읽어 온다.

[파일 출력 클래스]

  • FileOutputStram : 파일로 바이트 단위의 데이터를 출력한다.
  • FileWriter : 파일로 문자 단위의 데이터를 출력한다.

1) 파일 저장 위치

filetest 프로젝트 생성 후 그 아래에 파일 저장
data1.text 파일을 저장
다음과 같이 파일 저장

 

2) FileInputStream을 이용한 파일 입력

  • FileInputStream 생성자
    - FileInputStream(File file) : File 객체로부터 스트림 객체를 생성.
    - FileInputStream(String name) : 파일명을 이용해 스트림 객체를 생성.

  • FileInputStream 메소드
    - int read(): 입력 스트림으로부터 1바이트 데이터를 읽고, 읽은 데이터 바이트 수를 반환.
    - int read(byte [] b): 위와 비슷하지만 여러 바이트의 데이터를 읽고, 반환
    - int read(byte[] b, int off, int len): len 길이의 데이터를 읽고 배열 b[off] 위치로 저장하고 반환

※ 스트림을 이용한 데이터 읽기가 끝났으면 스트림을 닫아 주어야 하는데 이때 사용하는 메소드가 close()이다.

 

  • read() 메소드 이용해 파일의 데이터 읽어오기 예제_1
package filetest;

import java.io.FileInputStream;
import java.io.IOException;

public class Code211 {
	public static void main(String[] args) {
		FileInputStream fis = null;
		try {
			fis = new FileInputStream("data1.txt");
			int x;
			while ((x = fis.read()) != -1)
				System.out.print((char)x);
		} catch(IOException e) {
			System.out.println(e);
		} finally {
			try {
				fis.close(); // 예외 처리 필요
			} catch(IOException e) {
				System.out.println(e);
			}
		}
	}
}
_________________________________________________________________
결과
hello world
java programming

 

  • read() 메소드 이용해 파일의 데이터 읽어오기 예제_2(예외처리 효율적 처리 AutoCloseable)
package filetest;

import java.io.*;

public class Code212 {

	public static void main(String[] args) {
		int i;
		try (FileInputStream fin = new FileInputStream(inFile);)
		{
			do {
				i = fin.read(); // read form file
				if(i != -1) System.out.print(char)i);
			} while (i != -1);
		} catch(IOException e) {
			System.out.print("Error reading file");
		}

	}
}

 

 3) FileReader를 이용한 파일 입력

  • FileReader 생성자
    - FileReader(File file): File 객체를 통하여 FileReader 객체를 생성함.
    - FileReader(Stirng fileName): 파일명을 이용하여 FileReader 객체를 생성함.

  • FileReader 메소드
    - int read(): 파일로부터 한 문자를 읽어오고, 읽어온 데이터를 반환함.
    - int read(char[] cbug): 파일로부터 읽어온 문자들을 배열 cbut에 저장함.
    - int read(char[] cbuf, int offset, int length): length 개의 문자를 읽어와 cbuf[offse] 위치에 저장.

  • FileReader 클래스 이용 예제_01
package filetest;

import java.io.FileReader;
import java.io.IOException;

public class Code213 {

	public static void main(String[] args) {
		FileReader fis = null;
		try {
			fis = new FileReader("data3.txt");
			int x;
			while((x = fis.read()) != -1)
				System.out.print((char)x);
		} catch(IOException e) {
			System.out.println(e);
		} finally {
			try {
				fis.close();
			} catch(IOException e) {
				System.out.println(e);
			}
		}

	}
}
______________________________________________________
결과
hello world1
hello world2
hello world3

 

 

 

4.  파일 출력 클래스


 - 파일 출력은 파일로 데이터를 저장하는 것을 말한다.

 

 1) FileOutputStream을 이용한 파일 출력

  • FileOutputStream 생성자
    - FileOutputStream(File file): File 객체로부터 스트림을 생성함.
    - FileOutputStram(File file, boolean append): File 객체로부터 스트림을 생성하는 이미 존재하는 파일이면 append 제공
    - FileOutputStream(String name): 문자열로 파일명을 입력받아 스트림을 생성함.
    - FileOutputStream(String name, boolean append): 문자열 객체로부터 스트림을 생성하는데, 이미 존재하면 append 제공

  • FileOutputStream 메소드
    - void close(): 스트림을 닫음.
    - void flush(): 출력 버퍼를 강제로 비우고 데이터를 출력함.
    - abstract void write(int b): 데이터 b를 파일로 출력함.
    - void write(byte[] b): b 바이트 길이의 데이터를 파일로 출력함.
    - void write(byte[] b, int off, int len): 배열 b[off]부터 len 길이만큼의 데이터를 파일로 출력함.

  • void wirte 예제
package filetest;

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

public class Code214 {

	public static void main(String[] args) {
		String content = "Hello Java";
		byte[] bytes = content.getBytes();
		FileOutputStream fos = null;
		
		try {
			fos = new FileOutputStream("data4.txt");
			fos.write(bytes);
		} catch(IOException e) {
			e.printStackTrace();
		} finally {
			try { 
				fos.close();
			} catch(IOException e) {
				System.out.println(e);
			}
		}
	}
}
______________________________________________________________

결과값은 없지만 data4.txt가 실행한 경로에 생성되고 Hello Java 내용이 있다.

 

 2) FileWriter를 이용한 파일 출력

  • FileWriter 생성자
    - FileWriter(File file): File 객체로부터 스트림을 생성함.
    - FileWriter(File file, boolean append): File 객체로부터 스트림 생성하는데 이미 존재하면 append 제공.
    - FileWriter(String fileNaem): 문자열로 파일명을 입력받아 스트림을 생서함
    - FileWriter(String fileName, boolean append): 문자열 객체로부터 스트림 생성하는데 이미 존재하면 append 제공.
  • FileWriter 메소드
    - void write(char[] cbut): 문자배열 cbuf의 내용을 파일에 출력함.
    - void write(String str): 문자열 str을 파일에 출력함
    - void write(char[] cbuf, int off, int len): 문자열 cbuf[off]부터 len 개 문자를 파일에 출력함.
    - void write(String str, int off, int len): 문자열 str[off]부터 len 개 문자를 파일에 출력함.

  • 예제
package filetest;

import java.io.FileWriter;
import java.io.IOException;

public class Code215 {

	public static void main(String[] args) {
		char[] cbuf = {'J', 'A', 'V', 'A'};
		String lang = "Language";
		FileWriter fos = null;
		
		try {
			fos = new FileWriter("data5.txt");
			fos.write(cbuf);
			fos.write("\n........................................\n");
			fos.write(lang);
		} catch(IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fos.close();
			} catch(IOException e) {
				System.out.println(e);
			}
		}

	}
}

728x90
반응형

'Framwork > Java기초' 카테고리의 다른 글

Chapter 15. 스레드  (49) 2023.11.13
Chapter 14. 제네릭스와 컬렉션 프레임워크  (54) 2023.11.12
Chapter 12. 예외 처리  (20) 2023.08.15
Chapter 11. 패키지와 클래스들  (16) 2023.08.15
Chapter 10. 추상 클래스와 인터페이스  (16) 2023.08.12