바이트기반 스트림
- InputSteam
- OutputSteam
문자기반 스트림
- Reader
- InputStreamReader객체
==> 바이트 기반의 스트림을 문자 기반 스트림으로 변환
- InputStreamReader객체
- Writer
Input메서드
- read()
더 이상 읽어올 자료가 없으면 -1을 반환한다. - available()
읽어올 데이터의 수 - close()
Output 메서드
- write(읽어올 자료);
- write(읽어올 자료, 순서, 갯수)
"읽어올 자료" 배열의 내용 중 "순서" 번째부터 "갯수" 만큼 출력한다 - toByteArray()
- close()
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
public class ByteArrayIOTest01 {
public static void main(String[] args) {
byte[] inSrc = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
byte[] outSrc = null;
// 스트림 객체 생성
ByteArrayInputStream in = new ByteArrayInputStream(inSrc);
ByteArrayOutputStream out = new ByteArrayOutputStream();
int data; // 읽어온 자료가 저장될 변수
// read()메서드 이용하여 입력하기
// ==> 더 이상 읽어올 자료가 없으면 -1을 반환한다.
while ((data = in.read()) != -1) { // () 속 먼저 시작됨 data에 저장되어있는 값으로 -1인지 비교
// 읽어온 자료를 처리하는 내용을 이 영역에 기술한다.
// 읽어온 자료를 스트림으로 출력하기
out.write(data);
}
// 출력된 스트림 값을 배열로 변환하여 저장하기
outSrc = out.toByteArray();
// 입출력 작업이 끝나면 사용했던 작업(스트림 객체)를 반납한다.
try {
in.close();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 배열 값 출력해보기
System.out.println(" inSrc : "+Arrays.toString(inSrc)); // inSrc : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
System.out.println("outSrc : "+Arrays.toString(outSrc)); // outSrc : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
}
}
또 다른 byte배열을 이용한 출력
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
public class ByteArrayIOTest02 {
public static void main(String[] args) {
byte[] inSrc = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
byte[] outSrc = null;
byte[] temp = new byte[4]; // 4개 짜리 배열 생성
// 스트림 객체 생성
ByteArrayInputStream in = new ByteArrayInputStream(inSrc);
ByteArrayOutputStream out = new ByteArrayOutputStream();
try { // available() 읽어올 데이터가 있는지 확인
/*
while (in.available() > 0) {
// in.read(temp);
// out.write(temp);
//
// System.out.println("반복문에서 temp : "+Arrays.toString(temp));
// 반복문에서 temp : [0, 1, 2, 3]
// 반복문에서 temp : [4, 5, 6, 7]
// 반복문에서 temp : [8, 9, 6, 7]
// 방법 1
int len = in.read(temp); // 실제 읽어온 byte수를 반환
// temp배열의 내용 중 0번째부터 len갯수 만큼 출력한다
out.write(temp, 0, len); // temp라는 배열에 0번째 부터 len갯수만큼 출력
}
*/
// 방법2
int len;
while ((len = in.read(temp)) > 0) {
out.write(temp, 0, len);
}
outSrc = out.toByteArray();
in.close();
out.close();
} catch (
IOException e) {
// TODO: handle exception
}
System.out.println(" inSrc : " + Arrays.toString(inSrc)); // inSrc : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
System.out.println("outSrc : " + Arrays.toString(outSrc)); // outSrc : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 6, 7]
}
}
Close()
input output선언은 try-catch문 밖에서 이루어진다
finally로 정상적으로 실행이 되지않으면 종료시킴
import java.io.FileWriter;
import java.io.IOException;
public class FileIOTest05 {
public static void main(String[] args) {
FileWriter fw = null;
try {
// 입력할 코드
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
if(fw!=null) try {fw.close();}catch(IOException e) {}
}
}
}
System.in
콘솔(표준입출력장치)와 연결된 InputSteam객체
byte기반으로 출력
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class FileIOTest04 {
public static void main(String[] args) {
// Scanner s = new Scanner(System.in); // inputStream 형태로 키보드로 입력받은 데이터를 변환시켜서 쓸수 있게함
try {
System.out.print("입력 >> ");
int c = System.in.read();
System.out.println((char)c);
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
파일 읽기 / 출력 하기
파일 내용 읽기 (byte기반 스트림 이용)
byte기반이므로 한글은 읽어올 수 없음 (깨져서 출력) > 문자 기반으로 출력해야함
package kr.or.ddit.basic;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class FileIOTest01 {
// 파일 내용 읽기 ==> byte기반 스트림 이용
public static void main(String[] args) {
try {
// 파일 입력용 스트림 객체 생성 ==> 이 때 읽어올 파일 정보를 넣어준다.
// 방법1 ==> 읽어올 파일 정보를 File객체로 구성해서 넣어주기
// File file = new File("d:/d_other/test.txt");
// FileInputStream fin = new FileInputStream(file);
// 방법2 ==> 읽어올 파일 정보를 문자열로 직접 넣어준다.
FileInputStream fin = new FileInputStream(new File("d:/d_other/test.txt"));
int c; // 읽어온 데이터를 저장할 변수
while( (c=fin.read())!=-1 ) {
// 읽어온 데이터를 화면에 출력하기
System.out.print( (char) c ); // 문자로 출력받기 위해 char로 형변환
}
// 스트림 닫기
fin.close();
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
파일 자료 출력 > 저장하기 (byte기반 스트림 이용)
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileIOTest02 {
// 파일 내용 출력하기 > 파일 저장하기
public static void main(String[] args) {
try {
File file = new File("d:/d_other/out.txt"); // 존재하지 않은 파일은 새로 만들어짐
FileOutputStream fout = new FileOutputStream(file);
for(char c='A'; c<='Z';c++) {
fout.write(c);// c변수의 데이터를 파일로 출력한다.
}
fout.write('\n'); // 새로운 줄 추가
for(char c='a'; c<='z';c++) {
fout.write(c);// c변수의 데이터를 파일로 출력한다.
}
System.out.println("작업 완료");
fout.close(); // 스트림 닫기
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
파일 내용 읽기 (문자 기반 스트림 이용)
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
public class FileIOTest03 {
// 파일 내용 읽기 ==> 문자 기반 스트림을 이용
public static void main(String[] args) {
try {
// 파일 입력용 문자 기반 스트림 객체 생성
FileReader fr = new FileReader("d:/d_other/test.txt");
int c;
// 자료 읽기
while( (c=fr.read()) != -1 ) {
System.out.print( (char)c ); // 화면 출력 (한글도 정상적 출력)
}
fr.close();
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
파일 자료 출력 > 저장 (문자 기반 스트림 이용)
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class FileIOTest04 {
// 사용자가 입력한 내용을 그대로 파일로 저장하기
public static void main(String[] args) {
// System.in==> 콘솔(표준입출력장치)와 연결된 InputSteam객체
// Scanner s = new Scanner(System.in); // inputStream 형태로 키보드로 입력받은 데이터를 변환시켜서 쓸수 있게함
// InputStreamReader객체 ==> 바이트 기반의 스트림을 문자 기반 스트림으로 변환
try {
// 입력용 스트림 객체 생성
InputStreamReader isr = new InputStreamReader(System.in); // 스캐너처럼 사용가능
// 출력용 스트림 객체 생성
FileWriter fw = new FileWriter("d:/d_other/testChar.txt");
System.out.println("아무 내용이나 입력하세요. (입력의 끝은 Ctrl + Z 입니다)");
int c;
// 콘솔로 입력하기
while( (c=isr.read() )!=-1 ) {
fw.write(c); // 콘솔로 입력받는 데이터를 파일로 출력하기
}
System.out.println("저장 완료");
isr.close();
fw.close();
} catch (IOException e) {
// TODO: handle exception
}
}
}
구구단 파일 저장 예제
사용자로부터 출력할 단을 입력받아 구구단을 출력하는 프로그램을 작성하시오
단 구구단의 출력은 'd:/d_other/'폴더에 'gugudan.txt'파일에 저장되도록 한다
(출력한 단 입력은 Scanner로 입력 받는다.)
package kr.or.ddit.basic;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class FileIOTest05 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("출력할 단 숫자를 입력해주세요 >> ");
int num = scan.nextInt();
// finally로 정상적으로 실행이 되지않으면 종료시킴
// FileWriter fw = null;
try {
// 문자 기반 스트림
// FileWriter fw = new FileWriter("d:/d_other/gugudan.txt");
//
// fw.write( num + "단\n\n")
// for (int i = 1; i <= 9; i++) {
// int sum = num * i;
// String result = num + " * " + i + " = " + sum+"\n";
// fw.write(result);
// }
//
// fw.close();
// 바이트 기반 스트림
FileOutputStream fo = new FileOutputStream("d:/d_other/gugudan.txt");
for (int i = 1; i <= 9; i++) {
int sum = num * i;
String result = num + " * " + i + " = " + sum + "\n";
// fo.write(result.getBytes("utf-8"));
for (int j = 0; j < result.length(); j++) {
fo.write(result.charAt(j));
}
}
fo.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// try-catch문 밖에서 선언했을 경우 보통 finally에서 close해줌!!!!
// finally {
// if(fw!=null) try {fw.close();}catch(IOException e) {}
// }
}
}