자바I/O File 클래스 정리

황제낙엽 2019.07.29 02:30 조회 수 : 91

sitelink1 https://injunech.tistory.com/274 
sitelink2  
sitelink3  
sitelink4  
sitelink5  
sitelink6  

File 클래스 정리

java.io 패키지는 기존의 파일이나 폴더에 대한 제어를 하는 데 사용하는 File 클래스를 제공한다. 이 클래스를 이용해서 파일과 폴더에 대한 다양한 기능을 제공한다.

 

파일을 나타내는 객체를 생성하려면 다음과 같은 File 클래스의 생성자 함수를 이용한다.

 

* File 클래스의 생성자

File 클래스의 생성자 

 설명

File(File parent, String Child) 

 parent 객체 폴더의 child 라는 파일에 대한 File 객체를 생성한다.

File(String pathname) 

 pathname에 해당되는 파일의 File 객체를 생성한다. 

File(String parent, String, child) 

 parent 폴더 경로의 child라는 파일에 대한 File 객체를 생성한다.

File(URI uri)

 file uri 경로에 대한 파일의 File 객체를 생성한다. 

 

* File 클래스의 메소드

File 클래스의 메소드 

설명 

 File getAbsoluteFile()

 파일의 절대 경로를 넘겨준다. 

 String getAbsolutePath() 

 파일의 절대 경로를 문자열로 넘겨준다. 

 File getCanonicalFile() 

 파일의 Canonical 경로를 넘겨준다. 

 String getCanonicalPath()

 파일의 Canonical 경로를 문자열로 넘겨준다. 

 String getName()

 파일이나 폴더의 이름을 넘겨준다. 

 String getParent() 

 부모 경로에 대한 경로명을 문자열로 넘겨준다. 

 File getParentFile()

 부모 폴더를 File의 형태로 리턴한다. 

 String getPath() 

 파일의 경로를 문자열의 형태로 리턴한다. 

 long getTotalSpace() 

 하드디스크의 총 용량을 리턴한다.

 long getUsableSpace()

 하드디스크의 사용 가능한 용량을 리턴한다.

 long getFreeSpace()   하드디스크의 남은 공간을 리턴한다.

 int hashCode()

 hash code를 반환한다. 

 long lastModified() 

 해당 경로 파일의 최종 수정 일자를 반환한다. 

 long length()

 해당 경로 파일의 길이를 반환한다. 

 Path toPath()

 java.nio.file.Path 객체로 반환한다. 

 URI toURI() 

 URI 형태로 파일 경로를 반환한다. 

 File[] listRoots()

 하드디스크의 루트 경로를 반환한다. 

 String[] list() 

 경로의 파일들과 폴더를 문자열 배열로 반환한다. 

 String[] list(FilenameFilter filter) 

 filter에 만족되는 파일들과 폴더 이름을 문자열 배열로 반환한다. 

 File[] listFiles() 

 해당 경로의 파일들과 폴더의 파일을 배열로 반환한다. 

 File[] listFiles(FileFilter filter) 

 filter에 만족되는 파일들과 폴더를 File 배열로 반환한다. 

 File[] listFiles(FilenameFilter filter)

 filter에 만족되는 파일들과 폴더를 File 배열로 반환한다. 

 

* File 생성/수정/삭제 메소드

File 생성 수정 삭제 메소드 

 설명

 boolean createNewFile()

 주어진 이름의 파일이 없으면 새로 생성한다.

 static File createTempFile(String prefix, String suffix) 

 default temporary-file 디렉토리에 파일 이름에 prefix와 suffix를 붙여  임시파일을 생성한다.

 static File createTempFile(String prefix, String suffix, File directory) 

 새로운 임시파일을 파일 이름에 prefix와 suffix를 붙여 directory 폴더에 생성한다.

 boolean delete()

 파일이나 폴더를 삭제한다. 단, 폴더가 비어있지 않으면 삭제할 수 없다. 

 void deleteOnExit() 

 자바가상머신이 끝날 때 파일을 삭제한다. 

 boolean mkdir()

 해당 경로에 폴더를 만든다. 

 boolean mkdirs() 

 존재하지 않는 부모 폴더까지 포함하여 해당 경로에 폴더를 만든다.

 boolean renameTo(File dest) 

 dest 로 File 이름을 변경한다. 

 

* File 체크 메소드

 File 체크 메소드 

 설명 

  boolean exists()

 파일의 존재 여부를 리턴한다. 

  boolean isAbsolute() 

 해당 경로가 절대경로인지 여부를 리턴한다.

  boolean isDirectory() 

 해당 경로가 폴더인지 여부를 리턴한다. 

  boolean isFile() 

 해당 경로가 일반 file 인지 여부를 리턴한다.

  boolean isHidden()

 해당 경로가 숨김 file 인지 여부를 리턴한다.

 

* File 권한 메소드

File 클래스 권한 관련 메소드 

설명 

 boolean canExecute()

 파일을 실행할 수 있는지 여부를 리턴한다.

 boolean canRead() 

 파일을 읽을 수 있는지 여부를 리턴한다. 

 boolean canWrite()

 파일을 쓸 수 있는지 여부를 리턴한다. 

 boolean setExecutable(boolean executable)

 파일 소유자의 실행 권한을 설정한다.

 boolean setExecutable(boolean executable, boolean ownerOnly) 

 파일의 실행 권한을 소유자 또는 모두에 대해 설정한다. 

 boolean setReadable(boolean readable) 

 파일의 소유자의 읽기 권한을 설정한다. 

 boolean setReadable(boolean readable, boolean ownerOnly)

 파일의 읽기 권한을 소유자 또는 모두에 대해 설정한다. 

 boolean setReadOnly()

 파일을 읽기 전용으로 변경한다. 

 boolean setWritable(boolean writable)

 파일의 소유자의 쓰기 권한을 설정한다. 

 boolean setWritable(boolean writable boolean ownerOnly) 

 파일의 쓰기 권한을 소유자 또는 모두에 대해 설정한다. 

 

# 예제1 - 파일정보 가져오

import java.io.File;
import java.io.IOException;


public class FileTest {

    public static void main(String[] args) {
        
        // FileTest project 폴더에서 filefolder	est.txt  파일을 객체로 생성한다.
        // 는 이스케이프 문자로 인식되므로 \\ -> \ 로 사용한다.
        File file = new File("filefolder\\test.txt");

        // 경로에 파일이 존재하면
        if(file.exists()){
            
            try{
                
                System.out.println("getName: " + file.getName());  // 파일 이름 출력
                System.out.println("getPath: " + file.getPath());    // 파일 경로 출력 
                // 파일 절대 경로 출력              
                System.out.println("getAbsolutePath : "+ file.getAbsolutePath());  
                // 파일 정규 경로 출력
                System.out.println("getCanonicalPath : "+ file.getCanonicalPath()); 
                // 상위 폴더 출력
                System.out.println("getParent : " + file.getParent());   
                
           // 파일의 쓰기/읽기 권한 체크
          if(file.canWrite()) System.out.println(file.getName() + "은 쓸 수 있습니다.");
          if(file.canRead()) System.out.println(file.getName()+ "은 읽을 수 있습니다.");
                
                // 객체의 파일, 폴더 여부 체크
                if(file.isFile()){
                    System.out.println(file.getName() + "은 파일입니다.");
                }else if(file.isDirectory()){
                    System.out.println(file.getName() + "은 폴더입니다.");
                }else{
                    System.out.println(file.getName() + "은 파일도 폴더도 아닙니다.");
                }
                
          // 파일 내용 길이 출력
          System.out.println(file.getName() + "의 길이는 "+ file.length() + " 입니다.");
            
            }catch(IOException e){
                System.err.println(e);
            }
        
        }else{
            System.out.println("파일을 찾을 수 없습니다. ");
        }
    }
}

 

 

# 예제2 - 파일 목록 출력 예제

import java.io.File;


public class FileTest2 {

    public static void main(String[] args) {
        
        // 프로젝트 현재 폴더를 객체로 생성한다.
        File file = new File(".");
        
        // file이 존재하고 폴더일 경우
        if(file.exists() && file.isDirectory()){
            
            // 폴더의 파일/폴더 목록을 문자열 배열로 반환
            String[] fList = file.list();
            
            // 출력
            for(int i=0; i<fList.length; i++)
                System.out.println(fList[i]);
        
        }else{
            System.out.println("해당 경로는 폴더가 아닙니다.");
        }
    }
}

 

#예제3 - 하드디스크 정보 출력

import java.io.File;


public class FileTest3 {
    
    public static void main(String arg[]){
        
        String drive;
        double totalSpace, usedSpace, freeSpace, usableSpace;
        
        // 하드디스크의 루트 드라이버들을 배열로 반환한다.
        File[] roots = File.listRoots();
        
        for(File root : roots){
            
            // 루트 드라이버의 절대 경로
            drive = root.getAbsolutePath();
            
            // 하드디스크 전체 용량
            totalSpace = root.getTotalSpace() / Math.pow(1024, 3);
            // 사용가능한 디스크 용량
            usableSpace = root.getUsableSpace() / Math.pow(1024,3);
            // 여유 디스크 용량
            freeSpace = root.getFreeSpace() / Math.pow(1024,3);
            // 사용한 디스크 용량
            usedSpace = totalSpace - usableSpace;
            
            System.out.println("하드 디스크 드라이버 : " + drive);
            System.out.println("총 디스크 용량 : " + totalSpace + "GB");
            System.out.println("사용 가능한 디스크 용량 : " + usableSpace + "GB");
            System.out.println("여유 디스크 용량 : " + freeSpace + "GB");
            System.out.println("사용한 디스크 용량 : " + usedSpace+"GB");
            System.out.println();
            
        }
    }   
}

File[] roots = File.listRoots(); 는 하드디스크의 루트 드라이버를 배열로 반환한다.

- getUsableSpace()와 getFreeSpace() 는 결과가 같다.

- 사용한 디스크 용량은 총 용량에서 사용가능한 용량을 뺀 값이다.

- Math.pow(1024,3) 은 1024를 3승한 값이다.

 

 

번호 제목 글쓴이 날짜 조회 수
311 ResultSet 의 사이즈로 조회 결과가 있는지 확인 황제낙엽 2021.01.14 42
310 지정한 일자보다 하루 뒤로 설정하기 황제낙엽 2021.01.14 15
309 for, while 등의 loop구문에서 sleep하기 황제낙엽 2020.12.04 55
308 미디어 파일의 metadata를 읽자 (metadata-extractor) file 황제낙엽 2020.08.30 583
307 [HttpURLConnection] Authorization 헤더를 넣어 GET Request 황제낙엽 2020.08.12 376
306 직접 작성한 PropertiesUtil.java 황제낙엽 2020.07.21 35
305 [Online Book] manning사의 making java groovy 황제낙엽 2020.06.19 30
304 자바(JAVA) 어노테이션(Annotation) 황제낙엽 2020.04.10 29
303 [AWS, 웹 프로젝트] AWS+MySQL+SpringFrameWork5+JAVA8+ React+Gradle+Webpack+GIT+Jenkins file 황제낙엽 2020.04.08 48
302 Runtime 클래스의 exec() 함수 실행시의 실행 결과 수집 황제낙엽 2020.03.26 72
301 SQLite JDBC Driver 황제낙엽 2020.02.25 131
300 MySQL 한글깨짐현상 제거 ( UTF8 ) 황제낙엽 2019.12.08 573
299 java.util.ConcurrentModificationException 황제낙엽 2019.09.08 62
298 String, StringBuilder, StringBuffer file 황제낙엽 2019.08.03 58
297 String vs StringBuffer vs StringBuilder in Java 황제낙엽 2019.08.03 219
296 Calendar.set() - 날짜 설정하기, Calendar.add() - 날짜 더하기, Calendar.roll() - 그 부분만 날짜 더하기 황제낙엽 2019.08.02 89
» File 클래스 정리 황제낙엽 2019.07.29 91
294 파일 사이즈를 반환하는 유틸 함수 황제낙엽 2019.07.29 120
293 BufferedReader, BufferedWriter를 활용한 빠른 입출력 황제낙엽 2019.07.29 77
292 현재날짜, 현재시간을 원하는 형태로 출력하는(Format) 다양한 방법 file 황제낙엽 2019.07.29 66