C.R.U.D filework version project

2018. 5. 31. 22:38·오랜된 포스팅/Java

파일 생성,검색,수정,삭제


이번 포스팅은 java에서 파일을 생성하는 것과
생성된 파일을 관리하는 코드를 기록하려 합니다.

이 코드를 이용하게 되면
회원 관리와 같은 프로그램이 실행되고 있는 동안 
생성되고 수정되는 모든 데이터를
파일로 Export 와 Import의 기능을 가능하게 합니다.

추후 이러한 기능이 추가되어있는
Baseball player 멤버 관리 프로젝트를 포스팅하겠습니다.

mainClass
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
package main;
 
import java.util.Scanner;
 
import fileWork.fileWorkClass;
 
public class mainClass {
    // Input controller
    public static boolean controller(String conversion) {
        boolean b = true;
        for (int i = 0; i < conversion.length(); i++) {
            char c = conversion.charAt(i);
            if ((int) c < 49 || (int) c > 53) {
                b = false;
                break;
            }
        }return b;
    }
 
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        fileWorkClass file = new fileWorkClass();
 
        // member variable
        String conversion;
        int chNum;
 
        while (true) {
            System.out.println("C.R.U.D Filework Program");
            System.out.println("1. Create - 생성");
            System.out.println("2. Read - 검색");
            System.out.println("3. Update - 수정");
            System.out.println("4. Delete - 삭제");
            System.out.println("5. Exit - 종료");
 
            System.out.print("어느 작업을 하시겠습니까?\n>>>");
            conversion = sc.next();
            
            if(!(controller(conversion))) {
                System.out.println("입력값이 올바르지 않습니다.");
                continue;
            }
            
            chNum = Integer.parseInt(conversion);
            
            switch (chNum) {
            case 1: file.createFile();
                break;
            case 2: file.readFile();
                break;
            case 3: file.updateFile();
                break;
            case 4: file.deleteFile();
                break;
            default:
                System.out.println("\n프로그램을 종료합니다.");
                System.exit(0);
            }
 
        }
    }
}
 
Colored by Color Scripter
cs



fileWorkClass

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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
package fileWork;
 
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
 
public class fileWorkClass {
    Scanner sc = new Scanner(System.in);
 
    // Member variable
    private String fileName;
    private boolean check;
 
    // CreateFile
    public void createFile() {
        while (true) {
            System.out.print("생성할 파일 명을 입력하시오\n>>>");
            fileName = sc.next();
            boolean check = findedfile(fileName);
            if (check == true) {
                System.out.println("\n같은 파일이 존재합니다.\n");
                continue;
            }
            File newFile = new File("d:\\tmp\\" + fileName + ".txt");
            try {
                if (newFile.createNewFile()) {
                    System.out.println("\n파일을 생성하였습니다.\n");
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    // FindedFile
    public boolean findedfile(String fileName) {
        check = false;
        File dirFile = new File("d:\\tmp");
        String fileList[] = dirFile.list();
        for (int i = 0; i < fileList.length; i++) {
            if (fileList[i].equals(fileName + ".txt") == true) {
                check = true;
                break;
            }
        }
        return check;
    }
 
    // ReadFile
    public String[] readFile() {
        String dataArr[] = null;
        System.out.print("검색할 파일명을 입력하시오\n>>>");
        fileName = sc.next();
        File readFile = new File("d:\\tmp\\" + fileName + ".txt");
        check = checkBeforeReadFile(readFile);
        if (!check) {
            System.out.println("파일이 존재하지 않거나 읽을 수가 없습니다.");
            return null;
        }
        try {
            BufferedReader br = new BufferedReader(new FileReader(readFile));
            int count = 0;
            String str;
            while ((str = br.readLine()) != null) {
                count++;
            }
            br.close();
            dataArr = new String[count];
            int w = 0;
            br = new BufferedReader(new FileReader(readFile));
            while ((str = br.readLine()) != null) {
                dataArr[w] = str;
                w++;
            }
            br.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        for (int i = 0; i < dataArr.length; i++) {
            System.out.println("dataArr[" + i + "] = " + dataArr[i]);
        }
        return dataArr;
    }
 
    // CheckBeforeReadFile
    public boolean checkBeforeReadFile(File readFile) {
        if (readFile.exists()) {
            if (readFile.isFile() && readFile.canRead()) {
                return true;
            }
        }
        return false;
    }
 
    // UpdateFile
    public void updateFile() {
        String name, age, sex;
        System.out.print("업데이트를 할 파일 명을 입력하시오\n>>>");
        fileName = sc.next();
        File updateFile = new File("d:\\tmp\\" + fileName + ".txt");
        check = findedfile(fileName);
        if (check == false) {
            System.out.println("\n파일이 존재하지 않습니다.\n");
            return;
        }
        check = checkBeforeWriteFile(updateFile);
        if (check == false) {
            System.out.println("\n파일을 수정 할 수 없습니다.\n");
            return;
        }
        System.out.print("# 이름을 입력하시오\n>>>");
        name = sc.next();
        System.out.print("# 나이을 입력하시오\n>>>");
        age = sc.next();
        System.out.print("# 성별을 입력하시오\n>>>");
        sex = sc.next();
 
        PrintWriter pw;
        try {
            pw = new PrintWriter(new BufferedWriter(new FileWriter(updateFile, check)));
            pw.println(name + "-" + age + "-" + sex);
            pw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(fileName + ".txt 파일을 수정하였습니다.");
    }
 
    // CheckBeforeWriteFile
    public boolean checkBeforeWriteFile(File updateFile) {
        if (updateFile.canWrite()) {
            return true;
        }
        return false;
    }
 
    // DeleteFile
    public void deleteFile() {
        System.out.print("삭제할 파일명을 입력하시오\n>>>");
        fileName = sc.next();
        File deleteFile = new File("d:\\tmp\\" + fileName + ".txt");
        check = deleteFile.exists();
        if (!check) {
            System.out.println("\n삭제할 파일이 존재하지 않습니다.\n");
            return;
        } else {
            if (deleteFile.exists()) {
                deleteFile.delete();
                System.out.println("\n파일을 삭제하였습니다.\n");
            } else {
                System.out.println("\n파일을 삭제하지 못 했습니다.\n");
            }
        }
    }
}
 
Colored by Color Scripter
cs


..

..







저작자표시 비영리 변경금지 (새창열림)

'오랜된 포스팅 > Java' 카테고리의 다른 글

List Management Functions in java  (0) 2018.06.01
Baseball member management project(+File func)  (0) 2018.06.01
문자열(String)과 함께 사용되는 함수(method)  (0) 2018.05.28
ASCII 코드와 replace함수  (0) 2018.05.28
C.R.U.D. 프로그램 만들기 ver.2  (0) 2018.05.27
'오랜된 포스팅/Java' 카테고리의 다른 글
  • List Management Functions in java
  • Baseball member management project(+File func)
  • 문자열(String)과 함께 사용되는 함수(method)
  • ASCII 코드와 replace함수
Toycode
Toycode
오늘도 훌륭했던 시간을 보내길 바라며
  • Toycode
    오늘도 훌륭했어
    Toycode
  • 전체
    오늘
    어제
    • 분류 전체보기 (48)
      • 블록체인 (0)
      • 기초 CS 파훼하기 (2)
      • IT 트렌드 (1)
      • 오랜된 포스팅 (45)
        • Java (25)
        • SQL Developer (14)
        • eGovFramework (5)
        • IOS (1)
  • 링크

    • Online Resume
  • hELLO· Designed By정상우.v4.10.0
Toycode
C.R.U.D filework version project
상단으로

티스토리툴바