quilt code

[고급자바] IO (1) 본문

daily/고급자바

[고급자바] IO (1)

김뱅쇼 2023. 2. 13. 02:54

< File 객체 만들기 연습 >

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
package kr.or.ddit.basic;
 
import java.io.File;
import java.io.IOException;
 
public class T01FileTest {
    public static void main(String[] args) throws IOException {
        
        // File 객체 만들기 연습
        
        // 1. new File(String 파일 또는 경로명)
        //    => 디렉토리와 디렉토리 사이 또는 디렉토리와 파일명 사이의 구분문자는 '\'를 사용하거나 '/'를 사용할 수 있다.
        File file = new File("d:/D_Other/test.txt");
        
        System.out.println("파일명 : " + file.getName());
        System.out.println("파일 여부 : " + file.isFile());
        System.out.println("디렉토리(폴더) 여부 : " + file.isDirectory());
        System.out.println("---------------------------------------");
        
        File file2 = new File("d:/D_Other");
        
        System.out.print(file2.getName() + "은 ");
        if(file2.isFile()) {
            System.out.println("파일");
        } else if(file.isDirectory()) {
            System.out.println("디렉토리(폴더)");
    
        }
        System.out.println("---------------------------------------");
        
        // 2. new File(File parent, String child)
        //    => 'parent' 디렉토리 안에 있는 'child' 파일 또는 디렉토리를 의미함.
        File file3 = new File(file2, "test.txt");
        
        System.out.println(file3.getName() + "의 용량 크기 : " + file3.length() + "(bytes)");
        
        // 3. new File(String parent, String child)
        File file4 = new File(".\\D_Other\\test\\..""test.txt");    // 상대경로
        System.out.println("절대 경로 : " + file4.getAbsolutePath());   // 절대 경로 (윈도우 운영체제의 경우에는 D:로 시작해야)
        System.out.println("경로 : " + file4.getPath());               // 생성자에 설정해준 경로
        System.out.println("표준 경로 : " + file4.getCanonicalPath());   // 표준경로  (.. 같은 의미 없는 기호 생략 필요한 정보만 있음 깔끔하게 계산된 상태로 출력)
        System.out.println("-------------------------------------");
        
        /*
         *   디렉토리(폴더) 만들기
         *   
         *   1. mkdir() => File 객체의 경로 중 마지막 위치의 디렉토리를 만든다.
         *                   중간의 경로가 모두 만들어져 있어야 한다.
         *   2. mkdis() => 중간의 경로가 없으면 중간의 경로도 새롭게 만든 후 마지막 위치의 디렉토리를 만들어 준다.
         *           
         *   => 위 두 메소드 모두 만들기를 성공하면 true, 실패하면 false 반환함.
         * 
         */
        File file5 = new File("d:/D_Other/연습용");
        if(file5.mkdir()) {
            System.out.println(file5.getName() + "만들기 성공");
        } else {
            System.out.println(file5.getName() + "만들기 실패");    
        }
        System.out.println();
        
        File file6 = new File("d:/D_Other/test/java/src");
        if(file6.mkdirs()) {
            System.out.println(file6.getName() + "만들기 성공");
        } else {
            System.out.println(file6.getName() + "만들기 실패");    
        }
        System.out.println();
        
        
        
        
    }
 
}
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
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package kr.or.ddit.basic;
 
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
 
public class T02FileTest {
    public static void main(String[] args) throws IOException {
        
        File f1 = new File("d:/D_Other/sample.txt");
        File f2 = new File("d:/D_Other/sample.txt");
        
        if(f1.exists()) {
            System.out.println(f1.getAbsolutePath() + "은 존재합니다.");
        } else {
            System.out.println(f1.getAbsolutePath() + "은 없는 파일입니다.");
            
            if(f1.createNewFile()) {
                System.out.println(f1.getAbsolutePath() + "파일을 새로 만들었습니다.");
            }
        }
        
        if(f2.exists()) {
            System.out.println(f2.getAbsolutePath() + "은 존재합니다.");
        } else {
            System.out.println(f2.getAbsolutePath() + "은 없는 파일입니다.");
        }
        System.out.println("------------------------------------------");
        
        File f3 = new File("d:/D_Other");
        File[] files = f3.listFiles();
        for(File f : files) {
            System.out.print(f.getName() + " => " );
            
            if(f.isFile()) {
                System.out.println("파일");
            } else if(f.isDirectory()) {
                System.out.println("디렉토리(폴더)");
            }
        }
        System.out.println("==========================================");
        
        String[] strFiles = f3.list();
        for(String fileName :  strFiles) {
            System.out.println(fileName);
        }
        System.out.println("------------------------------------------");
        System.out.println();
        
        displayFileList(new File("d:/D_Other"));
        
    }
    
    /**
     *   지정된 디렉토리(폴더)에 포함된 파일과 디렉토리 목록을 보여주기 위한 메소드
     *   @param dir 목록 보고싶은 폴더객체
     */
    
    public static void displayFileList(File dir) {
        System.out.println("[" + dir.getAbsolutePath() + "] 디렉토리 내용" );
        
        // 디렉토리 안의 모든 파일 목록을 가져온다.
        File[] files = dir.listFiles();
        
        // 하위 디렉토리 정보를 저장할 List 객체 생성(File 배열의 인덱스 저장용)
        List<Integer> subDirList = new ArrayList<>();
        
        // 날짜정보를 출력하기 위한 포맷 설정하기
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd a hh:mm");
        
        for(int i=0; i<files.length; i++) {
            String attr = "";   // 파일의 속성정보(읽기, 쓰기, 히든파일, 디렉토리 구분정보)
            String size = "";   // 파일 용량
            
            if(files[i].isDirectory()) {
                attr = "<DIR>";
                subDirList.add(i); // 디렉토리인 경우 인덱스 정보 저장
            } else {
                size = files[i].length() + " ";
                attr = files[i].canRead() ? "R" : " ";
                attr += files[i].canWrite() ? "W" : " ";
                attr += files[i].isHidden() ? "H" : " ";
            }
            System.out.printf("%s %-5s %12s %s\n",
                    sdf.format(new Date(files[i].lastModified())),
                    attr, size, files[i].getName());
        } //for
        
        int dirCount = subDirList.size();
        int fileCount = files.length - dirCount;
        
        System.out.println(fileCount + "개의 파일, " + dirCount + "개의 디렉토리");
        System.out.println();
        
        for(int i=0; i<subDirList.size(); i++) {
            // 하위폴더의 내용들도 출력하기 위해 현재 메소드를 재귀호출하여 처리한다.
            displayFileList(files[subDirList.get(i)]);
        }
        
    
        
    }
}
cs

 

2) Byte Array Input

 

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
package kr.or.ddit.basic;
 
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
 
public class T03ByteArrayIOTest {
    public static void main(String[] args) throws IOException {
        
        byte[] inSrc = {0,1,2,3,4,5,6,7,8,9};
        byte[] outSrc = null;
        
        // 직접 복사하는 방법 
        outSrc = new byte[inSrc.length];  //메모리확보
        
        for(int i=0; i<inSrc.length; i++) {
            outSrc[i] = inSrc[i];
        }
        
        // arraycopy를 이용한 배열 복사 방법
        outSrc = new byte[inSrc.length];
        System.arraycopy(inSrc, 0, outSrc, 0, inSrc.length);
        System.out.println("arraycopy 후 outSrc => " + Arrays.toString(outSrc));
        
        
        ByteArrayInputStream bais = new ByteArrayInputStream(inSrc);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        
        int data = 0// 읽어온 데이터를 저장할 변수
        
        // read() 메소드 => byte단위 자료를 읽어와 int형으로 반환한다. 더이상 읽을 데이터가 없으면 -1을 반환함.
        while((data = bais.read()) != -1) {
            baos.write(data);   // 출력하기    
        }
        
        // 출력된 스트림 값을 배열로 변환해서 반환하기
        outSrc = baos.toByteArray();
        System.out.println("inSrc => " + Arrays.toString(inSrc));
        System.out.println("outSrc => " + Arrays.toString(outSrc));
        
        bais.close();
        baos.close();
        
    }
 
}
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
package kr.or.ddit.basic;
 
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
 
public class T04ByteArrayIOTest {
    public static void main(String[] args) throws IOException {
        
        byte[] inSrc = {0,1,2,3,4,5,6,7,8,9};
        byte[] outSrc = null;
        
        byte[] temp = new byte[4];  // 자료를 읽을 때 사용할 배열(버퍼용)
                
        ByteArrayInputStream bais = new ByteArrayInputStream(inSrc);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        
        int readBytes = 0// 읽은 바이트 수
        
        // read() 메소드 => byte단위 자료를 읽어와 int형으로 반환한다. 더이상 읽을 데이터가 없으면 -1을 반환함.
        while((readBytes = bais.read(temp)) != -1) {
            
            System.out.println("temp => " + Arrays.toString(temp));
            
            baos.write(temp, 0, readBytes);   // 출력하기    
        }
        
        // 출력된 스트림 값을 배열로 변환해서 반환하기
        outSrc = baos.toByteArray();
        System.out.println("inSrc => " + Arrays.toString(inSrc));
        System.out.println("outSrc => " + Arrays.toString(outSrc));
        
        bais.close();
        baos.close();
        
    }
 
}
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
package kr.or.ddit.basic;
 
import java.io.FileInputStream;
import java.io.IOException;
 
/**
 *   파일 읽기 예제
 */
 
public class T05FileStreamTest {
    public static void main(String[] args) {
        
        FileInputStream fis = null;
        
        try {
            fis = new FileInputStream("d:/D_Other/test.txt");
            
            int data = 0;
            
            while((data = fis.read()) != -1) {
                // 읽은 데이터 출력하기
                System.out.print((char) data);
            }
            
            
            
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                fis.close();
            } 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
package kr.or.ddit.basic;
 
import java.io.FileOutputStream;
import java.io.IOException;
 
/**
 *   파일 출력 예제
 */
 
public class T06FileStreamTest {
    
    public static void main(String[] args) {
        
        FileOutputStream fos = null;
        
        try {
            fos = new FileOutputStream("d:/D_Other/out.txt");
            for(char ch='a'; ch<='z'; ch++) {
                fos.write(ch);
            }
            
            System.out.println("파일에 쓰기 작업 완료...");
            
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            } 
        }
        
        
    }
 
}
cs

 

FileWriter(문자기반스트림) 예제)

 


사용자가 입력한 내용을 그대로 파일로 저장하기
콘솔(표준 입출력 장치)과 연결된 입력용 문자 스트림 생성
InputStreamReader : 바이트 기반 스트림을 문자 기반 스트림으로 변환해 주는 보조 스트림

 

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
package kr.or.ddit.basic;
 
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
 
 
public class T07FileWriterTest {
    public static void main(String[] args) {
 
        InputStreamReader isr = new InputStreamReader(System.in);
        
        FileWriter fw = null;
        
        try {
            
            System.out.println("아무거나 입력하세요.");
            
            fw = new FileWriter("d:/D_Other/testChar.txt");
            
            int data = 0;
            
            // 콘솔로 입력한 내용을 파일로 저장하기(입력의 끝 표시는 Ctrl + z 키를 누르면 된다.)
            while((data = isr.read()) != -1) {
                fw.write(data);  
            }
            
            System.out.println("입력 끝...");
            
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
 
    }
}
cs

 

'daily > 고급자바' 카테고리의 다른 글

[고급자바] IO (3)  (0) 2023.02.13
[고급자바] IO (2)  (0) 2023.02.13
[고급자바] Thread(6)  (0) 2023.02.13
[고급자바] Thread(5)  (0) 2023.02.10
[고급자바] Thread (4)  (0) 2023.02.10