KH정보교육원_웹 프로그래머 과정/Java

입출력 IO

calvin9150 2021. 2. 17. 20:45

IO는 input, output 이다. 

 

데이터를 입출력할때 두 대상을 연결할 무언가가 필요한데 그것이 스트림이다.

스트림은 단방향이라서 입력 스트림과 출력 스트림을 각각 둔다.

 

API 문서를 보면 InputStream클래스는 추상 클래스 이므로, 서브 클래스들을 사용하면 된다.

(OutputStream도 마찬가지)

 

 

 

 



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
79
80
81
82
83
84
85
package com.io.controller;
 
import java.io.File;
import java.io.IOException;
 
public class FileController {
 
    public static void main(String[] args) {
        //File객체 이용하기
        //클래스로 생성해서 사용을 한다.
        //생성자의 매개변수에 경로+파일명 대입
        //파일명만 쓴다 -> 디폴트 경로(프로젝트가 있는)에 파일이 생성
        File f = new File("test.txt");
        //여기까진 heap영역에 File 객체가 생성되기만 한 상태. 파일이 만들어 지진 않는다.
        
        //File클래스를 이용해서 파일 만들기
        try {
            f.createNewFile(); // 생성되면 true, 실패하면 false 반환
        } catch(IOException e) {
            e.printStackTrace();
        }
 
        //프로젝트 기준으로 절대경로 찾기
//        System.out.println(FileController.class.getResource("/").getPath()); "/"는 루트폴더 까지만 나오게 함
        String path = FileController.class.getResource("/").getPath();
        path = path.substring(0, path.lastIndexOf("bin"));
        System.out.println(path);
        File f2 = new File(path+"testpath.txt");
        try {
            f2.createNewFile();
        }catch(IOException e23) {
            e23.printStackTrace();
        }
        
        File dir = new File("C:\\Users\\gndnd\\Documents\\KH_Java\\dev\\13_io\\yalalala");
        //mkdir() : 지정한 마지막 폴더만생성. 마지막 경로의 상위 폴더들이 없으면 false반환. 성공시 true 반환.
        //mkdirs() : 지정한 모든 폴더 생성
        dir.mkdirs();
        
        //생성된 폴더, 파일을 삭제
        //delete() 메서드 사용. 마찬가지로 boolean 값반환
        File del = new File("test.txt");
        del.delete();
        
        //폴더 새로 만들고 파일 만들기
        File f3 = new File("test");
        f3.mkdir();
        String path2 = f3.getAbsolutePath();
        System.out.println(path2);
        File f4 = new File(path2+"/testttt.txt");
        try {
            f4.createNewFile();
        } catch(IOException e) {
            e.printStackTrace();
        }
        //폴더 새로 만들고 파일 만드는 메서드 생성
        createFile();
        
        //폴더 안의 모든 파일 가져오는 메서드
        File rootDir = new File("C:\\Users\\gndnd\\Documents\\KH_Java\\dev\\13_io");
        String[] fileNames = rootDir.list(); // filesNames 스트링 배열 안에 경로상 폴더,파일 이름 넣음
        for(String name : fileNames) {
            System.out.println(name);
        }
        
        //file에 대한 정보 출력
        System.out.println(f2.getName()); // 파일||폴더 명 출력
        System.out.println(f2.canExecute()); // 실행파일인지 확인
    }
    
    //폴더 새로 만들고 파일 만드는 객체
    public static void createFile() {
        File dir = new File("test55");
        dir.mkdir();
        File f = new File(dir.getName()+"/rclass");
        try {
            f.createNewFile();
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
    
 
    
}
cs

 

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
package com.io.controller;
 
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
 
public class FileIOStreamTest {
 
    public void saveFile() {
        //OutputStream : 램에 있는걸 빼서 저장하는 것이기 때문에
        //Stream은 반드시 반환 -> close() 메서드 사용
        // 예외처리 해야함 -> try ~ catch 이용
        FileOutputStream out = null;
        try {
            out = new FileOutputStream("testpath.txt");
            String msg = "lambda fighting 123";
            //write() 메서드 이용해서 파일 전송
            byte[] data = msg.getBytes();
            out.write(data);
        }  catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(null!=out) {
                    out.close();
                }
            } catch(IOException e) {
                e.printStackTrace();
                }
        }
    }
    
    public void loadFile() {
        //InputStream : 
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("testpath.txt");
            int data = -1//가져온 byte 데이터를 보관하는 변수
            //inputStream에서 파일에 저장된 내용을 더 이상 가져올게 없으면 -1 반환
            while((data=fis.read())!=-1) {
                System.out.println((char)data);
            }
            
        }catch(IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(fis!=null)fis.close();
            } catch(IOException e) {
                e.printStackTrace();
            }
        }
    }
    
}
 
cs

'KH정보교육원_웹 프로그래머 과정 > Java' 카테고리의 다른 글

제너릭스 Generics  (0) 2021.02.23
문자기반 스트림 Reader, Writer  (0) 2021.02.18
예외처리 Exception  (0) 2021.02.16
String 관련 클래스  (0) 2021.02.10
객체 Object  (0) 2021.01.29