Java

[Java] I/O Stream (InputStream / OutPutStream)

소댓 2023. 3. 28. 18:40

[ I/O Stream ]

 

* I/O Stream

1. 단방향성

2. 느리다

: 자바는 java.io에 io관련 클래스, 인터페이스가 모여 있음

 

- cache : 임시 저장소

-  buffer : 이기종 간의 속도 차이를 줄일 목적으로 가지는 메모리 영역

 

  byte Stream (형변환 연결 다리)   char Stream > 2byte씩 읽고 쓰기
InputStream BufferedInputStream(InputStream in)
FileInputStream
DataInputStream
ObjectInputStream
InputStreamReader Reader BufferedReader
FileReader
OutputStream BufferedOutputStream(OutputStream in)
FileOutputStream
DataOutputStream
ObjectOutputStream
OutputStreamWriter Writer BufferedWriter
FileWriter

 

 

 

- file 클래스 (exists, createNewFile, getAbsolutePath, isFile, isDirectory, list)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package day19;
 
import java.io.File;
 
import java.io.IOException;
 
// java.io
public class FileEx {
public static void main(String[] args) throws IOException {
    
    // URL : Uniform Resource Locator
    // URI : Uniform Resource Identifier
    
    // \ : window
    // / : unix, linux
    // \n : 엔터
    // \t : 탭
    // \\ : 일반 문자 \
    
    // D:\\app\\bluem\\product\\11.2.0\\dbhome_1 : 경로를 출력
    
    System.out.println("D:\\app\\bluem\\product\\11.2.0\\dbhome_1");
    
    String str = new String("c:\\");
    
    File f1 = new File("c:\\Hello2.java"); // 파일 경로를 파일 객체로 만듦
    
    // 파일이 있나? 없나? 확인
    System.out.println(f1.exists()?"파일있음":"파일없음");
    // 있으면 true, 없으면 false boolean 타입 리턴
    
    // 파일이 없으면 파일 생성
    if(!f1.exists()) {
        f1.createNewFile(); // 예외 처리 : throw
        System.out.println("파일을 생성합니다.");
    } else {
        System.out.println("파일이 존재합니다.");
    }
    System.out.println("--------------------");
    
    String path = f1.getAbsolutePath(); // 파일이 있는 경로 + 파일명
    System.out.println("파일 경로 : "+path);
    
    // isXXXX(); boolean 타입으로 리턴
    if(f1.isFile()) {
        System.out.println("파일입니다.");
    } 
    if(f1.isDirectory()) {
        System.out.println("디렉토리 입니다.");
    }
    
    System.out.println("------------------");
    
    File f2 = new File("c:\\dev\\eclipse");
    
    if(f2.isDirectory()) {
        System.out.println("디렉토리 입니다.");
    
    // 현재 디렉토리의 파일 목록을 배열로 리턴
    String[] list = f2.list();
    
    for(String x : list) {
        System.out.println(x);
        
    }
 
    }
    
    f1.delete(); // 파일을 지금 지워라
    
    f1.deleteOnExit(); // 끝나고 나면 파일을 지워라
    
    
}
    
    
}
 
cs

 

 

- FileInputStream, read()

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package day19;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
 
public class IOEx1 {
    public static void main(String[] args) throws IOException {
        
        // InputStream : System.in
        
        File f = new File("c:\\Hello.java");
        
        System.out.println(f);
        
        
        // 파일에 접근해서 한 바이트씩 읽어올 수 있는 능력이 있는 클래스 : FileInputStream
        
        FileInputStream fis = new FileInputStream(f);
        int v = 0;
        
        while ((v = fis.read()) != -1)  { // 파일의 끝에 도달한 게 아니라면
//        v = fis.read(); // 한 글자를 읽어서 ASCII CODE로 가져옴
        System.out.print((char)v);
 
        
        }
    }
}
 
cs

 

 

- FileOutputStream, write()

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package day19;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
 
public class IOEx2  {
    public static void main(String[] args) throws IOException {
        
        byte[] b = {'j''a''v''a'};
        
        File f = new File("c:\\javaout.txt");
        
        FileOutputStream fos = new FileOutputStream(f);
        
        fos.write(112); // 메모장에서 확인하면 'p' 출력
        
        
    }
}
 
 
cs

 

 

- FileInputStream, FileOutputStream, read(), write()

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package day19;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
 
public class IOEx3 {
    public static void main(String[] args) throws IOException {
        
        // c:\hello.java 파일의 내용을 읽어서 c:\\hello2.java 파일로 생성
        
        // 1. hello.java 파일 객체 f1 생성
        File f1 = new File("c:\\Hello.java");
        
        // 2. hello2.java 파일 객체 f2 생성
        File f2 = new File("c:\\Hello2.java");
    
        // 3. FileInputStream 객체를 생성
        FileInputStream fis = new FileInputStream(f1);
        FileOutputStream fos = new FileOutputStream(f2);
        
        // 4. f1을 이용해서 화면에 출력
        int v = 0;
        while ((v=fis.read()) != -1 ) {
            fos.write(v);
            System.out.print((char)v);
        }
    }
}
 
cs

 

 

- FileReader, FileWriter, read(), write()

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package day19;
 
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
 
public class IOEx4 {
    public static void main(String[] args) throws IOException {
        
        File f1 = new File("c:\\Hello.java");
        File f2 = new File("c:\\Hello3.java");
        
        // 파일 읽어오기
        FileReader fr = new FileReader(f1); // 예외 throws
        // 파일 쓰기
        FileWriter fw = new FileWriter(f2);
        
        // 읽어들이기
//        int value = fr.read(); // 예외 throws
        // System.out.println(value);
        
        int value = 0;
        while((value = fr.read()) != -1) {
            fw.write(value); // 파일에 저장
            System.out.print((char)value); // 한글 출력 가능(2byte씩 읽고 보내기 가능)
        }
    
        // buffer 비워짐..
        fw.flush(); // > 실행해보고 데이터 크기 0이면 flush 실행 필요 -> flush 실행해야 파일에 저장됨
        
    }
    
}
 
cs

 

 

- FileReader, FileWriter, read(), write()

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package day19;
 
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
 
public class IOEx5 {
    public static void main(String[] args) throws IOException {
        
        // 한글이 들어 있음
        // c:\test.txt 파일에 간단한 노래 가사를 적는다. > 메모장에서..
 
        File f = new File("c:\\test.txt");
        File f2 = new File("c:\\test3.txt");
        
        FileReader fr = new FileReader(f); // 읽어오기 (>아래 v=fr.read와 짝)
        FileWriter fw = new FileWriter(f2); // 새로 쓰기 (>아래 fw.wirte(v)와 짝)
        
        // c:\test.txt 파일을 읽어서 콘솔에 출력하고
        int v = 0;
        while( (v=fr.read()) != -1) {
            fw.write(v); // 파일에 쓰기
            System.out.println((char)v); // 한글 표시 가능
        }
        
        // c:\test3.txt 파일에 내용을 저장 시켜 보세요.
        fw.flush();
    }
    
}
 
cs

 

 

- FileReader, FileWriter, BufferedInputStream, BufferedOutputStream, read(), write()

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package day19;
 
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
 
public class IOEx6 {
    public static void main(String[] args) throws IOException {
        
        // BufferedInputStream : 버퍼라는 속도 완화 장치가 존재해서 속도가 더 빠름
        
        File f1 = new File("c:\\Hello.java");
        File f2 = new File("c:\\Hello4.java");
        
        // 파일에 접근해서 읽어오는 능력이 있는 클래스
        FileInputStream fis = new FileInputStream(f1); // 읽기
        FileOutputStream fos = new FileOutputStream(f2); // 쓰기
 
        // BufferedInputStream(InputStream in) 
        //             <== InputStream과 InputStream의 후손들을 생성자로 사용 가능
        
        BufferedInputStream bis =
                new BufferedInputStream(fis);
        BufferedOutputStream bos =
                new BufferedOutputStream(fos);
        
        // bis : Buffer + File 2가지 능력을 모두 가지고 있음
        int v = 0;
        
        while ( (v = bis.read()) != -1) { // v를 읽어온 것이 -1이 아니라면,
            bos.write(v); // 쓰기 -> 파일 사이즈 0이면 flush 하기
            System.out.print((char)v);
        }
    
        bos.flush();
    
}
}
 
cs

 

 

 

- FileReader, FileWriter, BufferedInputStream, BufferedOutputStream, read(), write(), readLIne()

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package day19;
 
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
 
public class IOEx7 {
    public static void main(String[] args) throws IOException {
        
        File f1 = new File("c:\\Hello.java");
        File f2 = new File("c:\\Hello5.java");
        
        // 파일에 접근할 수 있는 능력 : FileReader
        FileReader fr = new FileReader(f1);
        FileWriter fw = new FileWriter(f2);
        
        BufferedReader br = new BufferedReader(fr);
        BufferedWriter bw = new BufferedWriter(fw);
        
        // 한 줄씩 읽기 가능 : readLine > String 리턴
        String msg = null;
        
        while( (msg = br.readLine()) != null) { // 예외 던지기, 널이 아니라면 계속 반복해서 읽기
            bw.write(msg+"\n");
            System.out.println(msg); // 한 줄 통째로 읽기
        }
        
        bw.flush();
    }
}
 
cs