스트림(Stream)
자바는 데이터를 스트림 형태로 주고 받는다. 스트림(Stream)이란 데이터를 운반하는 데 사용되는 연결통로를 의미한다.
입력과 출력을 동시에 수행하려면 입력을 위한 입력스트림(input stream)과 출력을 위한 출력스트림(output stream)의 2개의 스트림이 필요하다.
java.io 패키지에 있는 클래스: FileInputStream, FileOutputStream, FileReader, FileWriter
파일을 읽기 위한 클래스 | 파일에 쓰기 위한 클래스 | |
이미지, 오디오 파일(1byte) | FileInputStream | FileOutputStream |
문자기반 파일(2byte-char) | FileReader | FileWriter |
FileInputStream
File의 내용을 byte 단위로 데이터를 읽는 InputStream을 상속한 클래스
FileInputStream 생성자
FileInputStream(File file) | 매개변수로 넘어온 file을 읽기 위한 InputStream 생성 |
FileInputStream(String name) | 매개변수로 넘어온 name 위치의 파일을 읽기 위한 InputStream 생성 |
FileInputStream 객체 생성
1. 첫 번째 방법
//#1. 파일객체 생성
File inFile = new File("infile.txt");
//#2. FileInputStream 객체 생성
InputStream fis = new FileInputStream(inFile);
2. 두 번째 방법
//#1. 파일 경로로 바로 FileInputStream 객체 생성
InputStream fis = new FileInputStream("infile.txt");
(File)InputStream 메서드의 활용
1. int read(): 한번에 1byte씩만 읽을 수 있음 (한 글자씩만 읽을 수 있음. 영문자 한 글자 = 1byte)
package study0206;
import java.io.*;
public class FileInputStreamTest1 {
public static void main(String[] args) {
//입력파일 생성
File inFile = new File("data.txt");
try{
//InputStream 생성
InputStream is = new FileInputStream(inFile);
int data; //읽은 데이터를 저장
//.read(): 1번에 1byte씩 읽을 수 있음
while((data=is.read())!= -1){ //-1: 파일의 끝을 나타냄
System.out.println("읽은 데이터: " + (char)data);
}
//InputStream 자원반납
is.close();
} catch(FileNotFoundException e){
System.out.println("파일을 찾을 수 없습니다.");
} catch(IOException e){
System.out.println("예상치 못한 에러가 발생했습니다.");
}
}
}
2. int read(byte[]): 한번에 block 형태로 읽을 글자 수를 정할 수 있음.
n-byte 단위 읽기(byte[])의 처음 위치에서부터 읽은 데이터 저장
byte[number]: 최대 'number' 만큼의 글자를 읽음
package study0206;
import java.io.*;
public class FileInputStreamTest2 {
public static void main(String[] args) {
//입력파일 생성
File inFile = new File("data.txt");
try{
//#2-1. n-byte단위 읽기 (byte[]의 처음 위치에서부터 읽은 데이터 저장)
byte [] byteArray1 = new byte[4]; //"Hell"(4) "oJav"(4) "a"(1) 로 끊어 읽게 됨
//InputStream 생성 - 빨대 꽂음
InputStream is = new FileInputStream(inFile);
int count1; //4 4 1
//.read(): 1번에 1byte씩 읽을 수 있음
while((count1 = is.read(byteArray1))!= -1){ //byteArray1 배열을 read의 매개변수로 넣음
for(int i = 0; i<count1; i++){
System.out.print((char)byteArray1[i]);
System.out.println(" :count=" + count1);
}
}
//InputStream 자원반납
is.close();
} catch(FileNotFoundException e){
System.out.println("파일을 찾을 수 없습니다.");
} catch(IOException e){
System.out.println("예상치 못한 에러가 발생했습니다.");
}
}
}
3. int read(byte[], int offset, int length) n-byte
n-byte 단위 읽기(length만큼 앞에서부터 읽어서 byte[] offset위치부터 넣어라)
byte[number]: 최대 'number'만큼의 글자를 읽음 (최소 offset + length)
offset: byte[]의 저장 시작 위치
length: length만큼의 길이를 읽음
- byte[6], offset = 2, length = 4일 때
F | i | l | e |
- byte[9], offset = 3, length = 6일 때
F | i | l | e | I | n |
package study0206;
import java.io.*;
public class FileInputStreamTest3 {
public static void main(String[] args) {
//입력파일 생성
File inFile = new File("data.txt");
try{
//InputStream 생성 - 빨대 꽂음
InputStream is = new FileInputStream(inFile);
int offset = 3, length = 6;
byte[] byteArray2 = new byte[9]; //offset+length
int count = is.read(byteArray2, offset, length); //offset:3, length:6
for(int i = 0; i<offset+length; i++){
System.out.print((char)byteArray2[i]);
}
//InputStream 자원반납
is.close();
} catch(FileNotFoundException e){
System.out.println("파일을 찾을 수 없습니다.");
} catch(IOException e){
System.out.println("예상치 못한 에러가 발생했습니다.");
}
}
}
FileOutputStream
File에 byte 단위로 데이터를 쓰는 OutputStream을 상속한 클래스
FileOutputStream 생성자
FileOutputStream(File file) | 매개변수로 넘어온 file을 쓰기 위한 OutputStream 생성, append=true인 경우 이어쓰기, append=false인 경우 새로 덮어쓰기 (default = false) |
FileOutputStream(File file, boolean append) | |
FileOutputStream(String name) | 매개변수로 넘어온 name 위치의 파일을 쓰기 위한 OutputStream 생성, append=true인 경우 이어쓰기, append=false인 경우 덮어쓰기 (default = false) |
FileOutputStream(String name, boolean append) |
FileOutputStream 객체 생성
1. 첫 번째 방법
//#1. 파일객체 생성
File outFile1 = new File("outfile1.txt");
File outFile2 = new File("outfile2.txt");
//#2. FileOutputStream 객체 생성
OutputStream fos1 = new FileOutputStream(outFile1); //덮어쓰기
OutputStream fos2 = new FileOutputStream(outFile2, true); //이어쓰기
2. 두 번째 방법
//#1. 파일경로로 바로 FileOutputStream 객체 생성
OutputStream fos1 = new FileOutputStream("outfile1.txt"); //덮어쓰기
OutputStream fos2 = new FileOutputStream("outfile2.txt", true); //이어쓰기
(File)OutputStream 메서드의 활용
1. void write(int b), void flush(), void close()
1-byte 단위 쓰기
출력을 위해서는 write후 flush()와 close()를 사용해주어야 한다.
flush(): write에 저장된 값을 출력함과 동시에 비워줌. flush()를 호출하지 않으면 내용이 버퍼에만 남고 파일에는 쓰이지 않는 상황이 발생할 수 있음
close(): OutputStream 자원 반납
package study0208;
import java.io.*;
public class FileOutputStream_1 {
public static void main(String[] args) {
try {
//입력파일 생성
File outFile = new File("C:\\Users\\user\\multicampus\\src\\study0208\\FileOutputStream1.txt");
//#1. 1-byte 단위 쓰기
OutputStream os1 = new FileOutputStream(outFile);
os1.write('J');
os1.write('A');
os1.write('V');
os1.write('A');
os1.write('\r'); //13 //생략가능
os1.write('\n'); //10 개행 /r/n
os1.flush();
os1.close();
} catch (FileNotFoundException e){
System.out.println("파일을 찾을 수 없습니다.");
} catch (IOException e){
System.out.println("그외 다른 에러가 발생했습니다.");
}
}
}
2. void write(byte[] b), void flush(), void close()
n-byte 단위 쓰기 (byte[]의 처음 위치에서부터 끝까지 출력)
package study0208;
import java.io.*;
public class FileOutputStream_1 {
public static void main(String[] args) {
try {
//입력파일 생성
File outFile = new File("C:\\Users\\user\\multicampus\\src\\study0208\\FileOutputStream1.txt");
//#1. 1-byte 단위 쓰기
OutputStream os1 = new FileOutputStream(outFile);
os1.write('J');
os1.write('A');
os1.write('V');
os1.write('A');
os1.write('\r'); //13 //생략가능
os1.write('\n'); //10 개행 /r/n
os1.flush();
os1.close();
//#2. n-byte 단위 쓰기(byte[]의 처음부터 끝까지 데이터를 쓰기)
OutputStream os2 = new FileOutputStream(outFile, true); //이어쓰기(내용 연결)
byte[] byteArray1 = "Hello!".getBytes(); //바이트 단위로 쪼갬
os2.write(byteArray1);
os2.write('\n');
os2.flush();
os2.close();
} catch (FileNotFoundException e){
System.out.println("파일을 찾을 수 없습니다.");
} catch (IOException e){
System.out.println("그외 다른 에러가 발생했습니다.");
}
}
}
3. void write(byte[] b, int off, int len), void flush(), void close()
n-byte 단위 쓰기 (byte[]의 offset 위치에서부터 length 개수를 읽어와 출력)
byte[number]: 최대 'number'만큼의 글자를 읽음 (최소 offset + length)
off: byte[]의 저장 시작 위치
len: length만큼의 길이를 읽음
byte[] byteArray2 = "Better the last smile than the first laughter.".getBytes();
→ off = 7, len = 8인 경우
B | e | t | t | e | r | t | h | e | l | a | s | t |
off = 7만큼 건너뛰고 len = 8만큼을 write한다.
(the last를 write함)
package study0208;
import java.io.*;
public class FileOutputStream_1 {
public static void main(String[] args) {
try {
//입력파일 생성
File outFile = new File("C:\\Users\\user\\multicampus\\src\\study0208\\FileOutputStream1.txt");
//#1. 1-byte 단위 쓰기
OutputStream os1 = new FileOutputStream(outFile);
os1.write('J');
os1.write('A');
os1.write('V');
os1.write('A');
os1.write('\r'); //13 //생략가능
os1.write('\n'); //10 개행 /r/n
os1.flush();
os1.close();
//#2. n-byte 단위 쓰기(byte[]의 처음부터 끝까지 데이터를 쓰기)
OutputStream os2 = new FileOutputStream(outFile, true); //이어쓰기(내용 연결)
byte[] byteArray1 = "Hello!".getBytes(); //바이트 단위로 쪼갬
os2.write(byteArray1);
os2.write('\n');
os2.flush();
os2.close();
//#3. n-byte 단위 쓰기(byte[]의 offset부터 length개의 byte 데이터를 쓰기)
OutputStream os3 = new FileOutputStream(outFile, true); //이어쓰기(내용 연결)
byte[] byteArray2 = "Better the last smile than the fist laughter".getBytes(); //바이트 단위로 쪼갬
os3.write(byteArray2, 7, 8); //the last
os3.flush();
os3.close();
} catch (FileNotFoundException e){
System.out.println("파일을 찾을 수 없습니다.");
} catch (IOException e){
System.out.println("그외 다른 에러가 발생했습니다.");
}
}
}
FileWriter
File의 내용을 char 단위로 출력을 수행하는 Writer을 상속한 클래스
FileWriter 생성자
FileWriter(File file)
FileWriter(File file, boolean append)
FileWriter(String fileName)
FileWriter(String fileName, boolean append)
FileWriter 객체 생성
//# FileWriter 객체 생성
File readerwriterFile = new File("src/pack02_javaio/sec05_files/ReaderWriterFile.txt");
Writer writer = new FileWriter(readerwriterFile);
FileWriter 메서드의 활용
package study0208;
import java.io.*;
public class FileReaderWriter {
public static void main(String[] args) {
//#파일객체 생성
File readerWriterFile = new File("C:\\Users\\user\\multicampus\\src\\study0208\\ReaderWriterFile.txt");
//#1.FileWriter를 이용한 파일 쓰기
try {
Writer writer = new FileWriter(readerWriterFile);
writer.write("안녕하세요\n");
writer.write("Hello");
writer.write('\r');
writer.write('\n');
writer.write("반갑습니다.", 2, 3); //습니다
writer.flush();
writer.close();
} catch (IOException e){
System.out.println("예상치 못한 에러 발생");
}
}
}
FileReader
File의 내용을 char 단위로 입력을 수행하는 Reader을 상속한 클래스
FileReader 생성자
FileReader(File file)
FileReader(String fileName)
FileReader 객체 생성
//# FileReader 객체 생성
File readerwriterFile = new File("src/pack02_javaio/sec05_files/ReaderWriterFile.txt");
Reader reader = new FileReader(readerwriterFile);
FileReader 메서드의 활용
package study0208;
import java.io.*;
public class FileReaderWriter {
public static void main(String[] args) {
//#파일객체 생성
File readerWriterFile = new File("C:\\Users\\user\\multicampus\\src\\study0208\\ReaderWriterFile.txt");
//#1.FileWriter를 이용한 파일 쓰기
try {
Writer writer = new FileWriter(readerWriterFile);
writer.write("안녕하세요\n");
writer.write("Hello");
writer.write('\r');
writer.write('\n');
writer.write("반갑습니다.", 2, 3); //습니다
writer.flush();
writer.close();
} catch (IOException e){
System.out.println("예상치 못한 에러 발생");
}
//#2. FileReader를 이용한 파일 읽기
try {
Reader reader = new FileReader(readerWriterFile);
int data;
while((data=reader.read())!=-1){
System.out.print((char)data);
}
} catch (IOException e){
System.out.println("예상치 못한 에러 발생");
}
}
}