본문 바로가기
JAVA

[JAVA] 파일처리 예시

by 주옹스 2020. 8. 18.

- File_Information_Print

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
package ex0818;
 
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
 
public class File_Info_Print {
    public static void main(String[] args) {
        String appDir = System.getProperty("user.dir"); //현재 프로그램을 개발하고 있는 위치
        System.out.println("현 작업 경로 : "+appDir); //현 작업 경로 : C:\study\work\JAVA -> 파일을 다 이 위치에 저장.
        
        String pathname = appDir+File.separator+"ex.txt"// seperator: 구분자 (os종류에 종속되지 않기 위해)
                                                          //-> window : \n , 리눅스\ , mac \\
        
        File f = new File(pathname);
        
        //exists() : 파일 또는 폴더가 존재하면 true
        if(!f.exists()) {
            System.out.println(pathname + " 파일이 존재하지 않습니다.");
            return;
        }
        
        try {
            System.out.println("파일정보...");
            System.out.println("파일명 : "+f.getName()); // ex.txt -> 파일명.확장자 (파일의 이름만 가져옴)
            System.out.println("경로명 : "+f.getPath()); // C:\경로\파일명.확장자
            System.out.println("절대경로명 : "+f.getAbsolutePath());    // C:\경로\파일명.확장자
            System.out.println("표준경로명 : "+f.getCanonicalPath());   // C:\경로\파일명.확장자
            System.out.println("부모경로 : " + f.getParent());         // C:\경로
            System.out.println("파일길이(long형) : " + f.length());    // 162
            System.out.println("파일생성일 : " + new Date(f.lastModified())); // 파일생성일 : Tue Aug 18 10:48:09 KST 2020
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
            String s = sdf.format(new Date(f.lastModified()));             
            System.out.println("파일생성일 : "+s);           // 파일생성일 : 2020-48-18 10:48:09
            System.out.println("읽기 속성 : "+f.canRead());  // 읽기 속성 : true
            System.out.println("쓰기 속성 : "+f.canWrite()); // 쓰기 속성 : true
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }
}
 
cs

 

 

 

 

 

 

 

- File_Rename

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 ex0818;
 
import java.io.File;
import java.util.Calendar;
 
public class File_Rename {
    public static void main(String[] args) {
        String appDir= System.getProperty("user.dir");
        String pathname = appDir +File.separator+"ex.txt";
        
        File f = new File(pathname);
        if(!f.exists()) {
            System.out.println(pathname +"존재하지 않음....");
            return;
        }
        
        // 확장자
        String fileExt = pathname.substring(pathname.lastIndexOf(".")); // .txt
        
        String newName = String.format("%1$tY%1$tm%1$td%1$tH%1$tM%1$tS", Calendar.getInstance());
        // tY : 캘린더에서 연도 , tm : 캘린더에서 월 , td : 캘린더에서 일
        // tH : 시 , tM : 분  , tS : 초                                                                     
        //System.out.println(newName); //20200818113612
        
        newName +=System.nanoTime()+fileExt;
        //System.out.println(newName); //20200818113642356203697505100.txt --> 바꿀 새로운 이름
        
        
        try {
            String newPath = appDir +File.separator+newName;
            File dest = new File(newPath);
            f.renameTo(dest);
            System.out.println("파일명 변경 완료..."); //파일명 변경완료... 나오면 두번다시 실행불가.
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 
cs

 

 

 

 

 

 

 

- File_Delete

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 ex0818;
 
import java.io.File;
 
 
public class File_Delete {
    public static void main(String[] args) {
        
        String pathname = "C:" +File.separator+"user"+File.separator+"ex.txt";
        
        try {
            File f = new File(pathname);
            if(!f.exists()) {
                System.out.println(pathname +"존재하지 않음....");
            }
            
            
            // 파일이나 폴더는 한번에 하나씩 삭제 가능.
            // 폴더는 비어있지 않으면 삭제 불가.
            boolean b = f.delete();
            if(b) {
                System.out.println("삭제 완료...");
            }else{
                System.out.println("삭제 실패...");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 
cs

 

 

 

 

- File_Directory_Print

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 ex0818;
 
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
 
 
public class File_file_directory_Print {
    public static void dirList(String pathname) {
        File f = new File(pathname);
        File[] ff = f.listFiles(); //경로에 존재하는 모든 파일 및 폴더
        
        if(ff==null || ff.length == 0) {
            return;
        }
        
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String s;
            
            for(File file : ff) {
                s = sdf.format(new Date(f.lastModified()));
                if(file.isFile()) {
                    System.out.println(file.getName()+"\t");
                    System.out.print(s+"\t");
                    System.out.println(file.length());
                }else if(file.isDirectory()){
                    System.out.println(file.getName()+"...");
                    dirList(file.getCanonicalPath()); // 재귀호출
                    
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) {
        
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String s;
        
        try {
            //C:\windows
            System.out.print("경로 ? ");
            s = br.readLine();
            dirList(s);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 
cs

 

 

 

 

 

 

 

- File_Make_Directory

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
package ex0818;
 
import java.io.File;
 
 
public class File_Make_directory {
    public static void main(String[] args) {
        String pathname = "C:"+File.separator+"user"+File.separator+"ex";
        
        try {
            File f = new File(pathname);
            
            if(!f.exists()) {
                // 폴더 만들기
                // f.mkdir(); // 상위폴더가 없으면 만들어지지 않는다 ==> user라는 폴더가 없기 때문에 생성되지 않음.
                f.mkdirs(); // 상위 폴더가 없으면 상위폴더도 생성
                System.out.println("폴더를 생성했습니다.");
            }
            System.out.println(pathname);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 
cs

 

 

 

 

 

 

 

 

 

 

- File_Remove_Directory

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 ex0818;
 
import java.io.File;
 
public class File_Remove_directory {
    
    public static void removeDir(String pathname) {
        try {
            File f = new File(pathname);
            if(f.isDirectory()) {
                removeSubDir(pathname);
            }
            f.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    private static void removeSubDir(String pathname) { //폴더 밑에 있는 자식까지 재귀로 모두 지움
        File[] ff = new File(pathname).listFiles();
        try {
            if(ff.length == 0)return;
            
            for(File f: ff) {
                if(f.isDirectory()) {
                    removeSubDir(f.getPath());
                }
                f.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    public static void main(String[] args) {
        String pathname = "C:"+File.separator+"user";
        
        removeDir(pathname);
        System.out.println("삭제 완료...");
    }
}
 
cs

 

 

'JAVA' 카테고리의 다른 글

[JAVA] 람다식(Lambda Expression)  (0) 2020.08.25
[ JAVA ] Thread  (0) 2020.08.20
[JAVA] 입출력 스트림 (I/O Stream)  (0) 2020.08.18
[JAVA] 생성자  (4) 2020.08.11
[JAVA]인터페이스 (Interface)  (1) 2020.08.11