1. 스트림(Stream) 이란?
- 데이터의 '흐름' 또는 '연결 통로'
2. 흐름이란
- Source -> 데이터의 흐름 -> Destination(키보드, 파일, 브라우저 / 모니터, 프린터, 파일, 브라우저)
3. 표준 입출력 스트림
- 키보드(System.in) -> 모니터(System.out)
4. 특징
- FIFO (First In First Out)
- 단방향성
- 지연성
- 유연성 : 노드(근원) 스트림을 목적에 맞게 필터링 하는것
ex)
BufferedReader br = new BufferedReder(new InputStreamReader(System.in));
5. 구분
- 읽고 쓰는 단위
ㄴ 1byte 스트림 (바이트 스트림 : 문자를 제외한 나머지) : XXXInputStream, XXXReader
ㄴ 2byte 스트림 (문자 스트림 : 문자를 입출력) : XXXReader, XXXWriter
- 입출력
ㄴ 입력 스트림 : XXXInputStream, XXXReader
ㄴ 출력 스트림 : XXXOutputStream, XXXWriter
- 기능
ㄴ 노드 스트림 : 데이터의 근원지나 목적지에 직접 연결된 스트림 (System.in...등등)
ㄴ Bridge 스트림 : 1byte -> 2byte (InputStreamReader, OutputStreamWriter)
ㄴ 필터 스트림 : 사용 목적에 맞게 가공한 스트림 (BufferedReader...등등)
* IO 스트림
import java.io.*;
class A
{
InputStream is;
OutputStream os;
A(){
is = System.in; //키보드
os = System.out; //모니터
}
void m1(){
try{
int i = 0;
int b = 0;
while((b = is.read()) != -1){
if(b == 13) break;
os.write(b);
os.flush();
i++;
}
System.out.println("m1() i : " + i);
}catch(IOException ie){
}finally{
try{
if(is != null) is.close();
if(os != null) os.close();
}catch(IOException ie){}
}
}
void m2(){
try{
int i = 0;
int count = 0;
byte[] bs = new byte[8];
while((count = is.read(bs)) != -1){
os.write(bs, 0, count);
i++;
}
System.out.println("m2() i : " + i);
}catch(IOException ie){
}finally{
try{
if(is != null) is.close();
if(os != null) os.close();
}catch(IOException ie){}
}
}
public static void main(String[] args)
{
A a = new A();
a.m1();
a.m2();
}
}
* File IO 스트림
import java.io.*;
class B {
FileInputStream fis;
FileOutputStream fos;
String fName = "IO.jpg";
String fCopy = "IOCopy.jpg";
B() {
try {
fis = new FileInputStream(fName); // 파일
fos = new FileOutputStream(fCopy);
} catch(FileNotFoundException fe) {
System.out.println(fName + "파일이 존재하지 않음.");
}
}
void m() {
try {
int count = 0;
byte[] bs = new byte[8];
while((count = fis.read(bs)) != -1)
fos.write(bs, 0, count);
System.out.println(fCopy + "로 복사 완료.");
} catch(IOException ie) {
} finally {
try {
if(fis != null) fis.close();
if(fos != null) fos.close();
} catch(IOException ie){}
}
}
public static void main(String[] args) {
B b = new B();
b.m();
}
}
* Data IO 스트림
import java.io.*;
class B {
String fTarget = "target.txt";
FileInputStream fis; // 노드
FileOutputStream fos;
DataInputStream dis; // 필터
DataOutputStream dos;
File file;
B() {
try {
file = new File(fTarget);
if(!file.exists()) file.createNewFile();
fis = new FileInputStream(fTarget);
fos = new FileOutputStream(fTarget);
dis = new DataInputStream(fis);
dos = new DataOutputStream(fos);
} catch(FileNotFoundException fe) {
System.out.println(fTarget + " 파일이 없음");
} catch(IOException ie) {}
}
void write() {
boolean bl = true; // 1
byte b = 10; // 1
short s = 20; // 2
char c = 'A'; // 2
int i = 30; // 4
long lo = 40L; // 4
float f = 50.0f; // 4
double d = 60.0; // 8
String str = "가나"; // 8
try {
dos.writeBoolean(bl);
dos.writeByte(b);
dos.writeShort(s);
dos.writeChar(c);
dos.writeInt(i);
dos.writeLong(lo);
dos.writeFloat(f);
dos.writeDouble(d);
dos.writeUTF(str);
dos.flush();
System.out.println("기본형 8개와 UTF-8 이 써짐 (크기: " + file.length() + ")\n");
} catch(IOException ie) {}
}
void read() {
System.out.println(fTarget + " 파일의 내용");
try {
boolean bl = dis.readBoolean();
byte b = dis.readByte();
short s = dis.readShort();
char c = dis.readChar();
int i = dis.readInt();
long lo = dis.readLong();
float f = dis.readFloat();
double d = dis.readDouble();
String str = dis.readUTF();
System.out.println("bl: " + bl);
System.out.println("b: " + b);
System.out.println("s: " + s);
System.out.println("c: " + c);
System.out.println("i: " + i);
System.out.println("lo: " + lo);
System.out.println("f: " + f);
System.out.println("d: " + d);
System.out.println("str: " + str);
} catch(IOException ie) {
} finally{
try{
if(dis != null) dis.close();
if(dos != null) dos.close();
if(fis != null) fis.close();
if(fos != null) fos.close();
}catch(IOException ie){}
}
}
public static void main(String[] args) {
B b = new B();
b.write();
b.read();
}
}
* File R/W 스트림
import java.io.*;
class C {
String fName = "B.java";
String fCopy = "BCopy.txt";
Reader r;
Writer w;
C() {
try {
r = new FileReader(fName);
w = new FileWriter(fCopy);
m();
} catch(FileNotFoundException fe) {
System.out.println(fName + "파일이 존재하지 않음.");
}
catch(IOException ie) {}
}
void m() {
int count = 0;
char[] chr = new char[8];
try {
while((count = r.read(chr)) != -1)
w.write(chr, 0 , count);
w.flush();
System.out.println(fCopy + "로 복사 완료.");
} catch(IOException ie) {}
finally {
try {
if(r != null) r.close();
if(w != null) w.close();
} catch(IOException ie) {}
}
}
public static void main(String[] args) {
new C();
}
}
* Buffer R/W스트림
import java.io.*;
class A {
String fName = "A.java";
String fCopy = "A.txt";
final static int BUFFER_SIZE = 1024;
FileInputStream fis; // 노드 1byte
FileOutputStream fos;
BufferedInputStream bis; // 필터 1byte
BufferedOutputStream bos;
A() {
try {
fis = new FileInputStream(fName);
fos = new FileOutputStream(fCopy);
bis = new BufferedInputStream(fis, BUFFER_SIZE);
bos = new BufferedOutputStream(fos, BUFFER_SIZE);
} catch(FileNotFoundException fe) {}
}
void readWrite() {
try{
int count = 0;
byte[] bs = new byte[256];
while((count = bis.read(bs)) != -1){
bos.write(bs, 0, count);
}
bos.flush();
System.out.println(fCopy + " 파일 복사 완료");
}catch(IOException ie){
}finally{
try{
if(bis != null) bis.close();
if(bos != null) bos.close();
if(fis != null) fis.close();
if(fos != null) fos.close();
}catch(IOException ie){}
}
}
public static void main(String[] args) {
new A().readWrite();
}
}
|
1 byte 기반 스트림 |
2 byte 기반 스트림 |
||
추상클래스 |
InputStream |
OutputStream |
Reader |
Writer |
노드스트림 |
FileInputStream |
FileOutputStream |
FileReader |
FileWriter |
브릿지스트림 |
|
|
InputStream Reader |
OutputStream Writer |
필터스트림 |
DataInputStream |
DataOutput Stream |
BufferedReader |
BufferedWriter |
BufferedInput Stream |
BufferedOutput Stream |
PrintReader |
PrintWriter |
|
ObjectInput Stream |
ObjectOutput Stream |
|
|
* 주요 스트림
- 노드스트림 : 기본적으로 한 바이트, 한 문자 단위로 데이터를 계속 읽고, 쓰고를 반복해서 데이터의 끝(-1)을 만나
면 종요한다. 즉, 반복문 (횟수를 모르므로 while) 을 사용해서 읽기와 쓰기를 반복해준다
* 파일 (File) 클래스
- String getName() : 파일명 혹은 디렉토리의 이름 얻어 오는 메소드
- String getPath() : 파일 혹은 디렉토리의 상대경로
- String getAbsolutePath() : 파일 혹은 디렉토리의 절대 경로
예] src\\test.txt - 상대경로 : src\test.txt
절대경로 : d:\java\javaProj\src\test.txt
- long length() : 파일의 크기(바이트), 디렉토리는 크기는 0 반환, 또한 존재하지 않은 파일도 0 반환
- String getParent() : 상위 부모의 경로,File개체 생성시 상위 부모명이 주어지지 않으면 null반환
상위 디렉토리 얻어 올때 File클래스의 생성자 중 File(String parent, String child) 를
사용하면 parent매개변수에 지정한 값을 무조건 얻어 온다
그러나 File(String pathname) 를 사용해서 File객체 생성시 getParent()메소드는
null을 반환한다. 단, 절대경로로 디렉토리를 넣어주면 해당 상위 디렉토리를 얻어온다
- boolean isFile() : 파일이면 true 아니면 false
- boolean isDirectory() : 디렉토리면 true,아니면 false
- boolean exists() : 디렉토리 혹은 파일이 존재 하면 true 아니면 false
- boolean delete() : 디렉토리 혹은 파일삭제 성공시 true 실패하면 false
만약 디렉토리인 경우 디렉토리가 비어 있어야 한다.
- boolean canRead() : 읽기 가능하면 true 아니면 false
- boolean canWrite() : 쓰기 가능하면 true,아니면 false
- long lastModified() : 파일이나 디렉토리가 최근 수정된 날짜를 1970년 1월 1일 0시0분0초부터
현재까지 흘러온 시간을 1000분의 1초 단위로 반환
- boolean mkdir() : 디렉토리 생성
(부모 디렉토리가 있어야 함, 아니면 자식 디렉토리값만 File 생성자의 인자로 주어야 한다)
예] new File("src/tmp") 혹은 new File("tmp")
- boolean mkdirs() : 부모 디렉토리가 없더라도 부모 디렉토리까지 생성
- boolean ranameTo(File dest) : 파일 이름 변경 성공하면 true,아니면 false
- String[] list() : 디렉토리에 있는 파일 및 디렉토리 목록 반환
- File[] listFiles() : 디렉토리에 있는 파일 및 디렉토리 목록 반환(File개체 로 반환)
'개발 > JAVA' 카테고리의 다른 글
23. JAVA JDBC (Java Database Connectivity) - 1 (0) | 2020.06.08 |
---|---|
22. JAVA Network 네트워크 (0) | 2020.06.08 |
20. JAVA 쓰레드 (Thread) (0) | 2020.06.08 |
19. JAVA 예외(Exception) / try~catch~finally (0) | 2020.06.08 |
18. JAVA 클래스간 형변환 / 업캐스팅 / 다운캐스팅 / 내부클래스 (InnerClass) (0) | 2020.06.08 |