자바 입/출력 File 클래스

자바 입/출력 File 클래스


File 클래스

  1. 멤버 변수
    멤버변수 내용

static String pathSeparator 경로에 대한 구분자, ‘:’<- window환경에서의 표시
static char pathSeparatorChar 경로에 대한 구분다 char형
static String separator 파일 경로에 대한 구분자, \
static char separatorChar 파일 경로에 대한 구분자 char형

  1. 생성자
    생성자 내용

File(File parent, String child) 상위폴더 parent를 경로로 하는 파일명 child와 연결하는 생성자
File(String pathname) pathname을 전체 경로로 하는 파일에 대한 연결 생성자
File(String parent, String child) 상위폴더 parent를 경로로 하는 파일명 child와 연결하는 생성자
File(URL url) url의 파일과 연결하는 생성자

  1. 메소드
    메소드 내용

boolean canRead() 파일을 읽을수 있는지 확인
boolean canWrite() 파일에 데이터를 쓸수 있는지 확인
boolean createNewFile() 새로운 파일을 생성
static File createTempFile
(String prefix, String suffix) temp 파일을 prefix 접두어와 suffix 접미어를 붙여 생성
static File createTempFile temp 파일을 prefix 접두어와 suffix 접미어를 붙여
(String prefix, String suffix, File directory) 디렉토리 경로에 생성
boolean delete() 파일을 즉시 삭제
void deleteOnExit() 프로그램 종료시 파일 삭제
boolean exists() 파일의 존재 유무를 확인
File getAbsoluteFile() 파일의 절대 경로를 File 객체로 얻어옴
String getAbsolutePath() 파일의 절대 경로에 대한 경로
File getCanonicalPath() 파일의 상대경로를 File 객체로 획득
String getCanonicalPath() 파일의 상대 경로에 대한 경로
String getName() 파일이름
String getParent() 파일의 상위 폴더까지의 경로
File getParentFile() 파일의 상위 폴더까지의 경로 File 객체
String getPath() 현재 파일의 경로
boolean isAbsolute() 절대경로인지 확인
boolean isDorectory() 디렉토리인지 확인
boolean isFile() 파일인지 확인
boolean isHidden() 숨김파일인지 확인
long lastModified() 최종수정 시간 획득
long length() 파일의 크기 획득
String[] list() 해당 파일이 폴더일 경우 그 속의 모든 파일이나 폴더의
리스트를 문자열 배열로 획득
String[] list(SilenameFilter filter) 해당 파일이 폴더일 경우 그속의 내용들 중 filter 객체의
구현한 내용을 필터링
File[] listFiles(FileFilter filter) 해당파일이 폴더일경우 그속의 내용을 파일 배열로 얻어
오는데 filter 객체에 구현한 내용을 필터링
File[] listFiles(FilenameFilter filter) 해당파일이 폴더일경우 그속의 내용을 파일 배열로 얻어
오는데 filter 객체에 구현한 내용을 필터링
static File[] listRoots() 현재 시스템의 루트 경로를 File 객체 배열로 획득(C\, D\등)
boolean mkdir() 폴더를 생성
boolean mkdirs() 폴더들을 생성
boolean renameTo(File dest) 파일 이름을 dest로 변경
boolean setLastModified(long tile) 최종 수정 시간 수정
boolean setReadOnly() 읽기 전용 파일로 만듦
URL toURL() 파일의 URL경로를 획득

Fileclass 예제

Ex1 )

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.io.*;

public class Java {
public static void main(String[] ar) {
File f = new File("c:\\java\\work");
// File객체의 생성자를 생성 생성자의 매개변수로 폴더 생성
if (f.exists())
f.delete();
// 생성자의 매개변수의 폴더가 있다면 매개변수의 폴더를 지운다
try {
Thread.sleep(3000);
} catch (InterruptedException ee) {
}
System.out.println("시점");
if (!f.exists())
f.mkdir();
// 만약 폴더가 없다면 폴더를 만든다 .
}
}

Ex2 )

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
import java.io.*;

public class Java {
public static void main(String[] ar) {
File f = new File("c:\\java\\work");
// File객체의 생성자를 생성 생성자의 매개변수로 폴더 생성
if (!f.exists())
f.mkdir();
// 만약 폴더가 없다면 폴더를 만든다 .
try {
Thread.sleep(3000);
} catch (InterruptedException ee) {
}
File f1 = new File(f, "abc.txt");
// File 클래스의 생성자 f 와 "abc.txt" 라는 파일을 지정
if (!f.exists()) { // 만약 파일이 없다면
try {
f1.createNewFile();
// 생성자의 지정한 파일을 만든다
} catch (IOException io) {
}
if (f1.canWrite())
f1.setReadOnly();
// 만약 파일이 쓸수 있게 지정되었다면 읽기전용 파일로 만든다
}
}
}

Ex3 )

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
import java.io.*;

public class Java {
public static void main(String[] ar) {
/*
* File f = new File("c:\\java\\work"); boolean bool = f.mkdir();
* if(bool){ System.out.println("잘 만들어 졌다."); }else{
* System.out.println("만들기 실패다."); }
*/
// work폴더에 abc.txt가 없다면
// abc.txt라는 파일은 없다 . 라는 문구가 뜨면되고
// work폴더에 abc.txt가 있다면
// 파일명 : abc.txt
// 파일크기 : 0kb
// 최종 수정일 : Jul 1 2011, 10:00:00이라고 출력하면 된다 .
// 프로그램 종료시 삭제한다.
File f1 = new File("c:\\java\\work\\abc.txt");
// 객체를 생성
if (!f.exists()) {// 만약 파일이 있다면
f.deleteOnExit();// 종료 시에 삭제하도록 명령을 내려둔다
System.out.println("파일명 : " + f.getName());
System.out.println("파일경로 : " + f.getPath());
System.out.println("파일경로 : " + f.getParent());
System.out.println("파일크기 : " + f.getLength() + "kb");
System.out
.println("파일크기 : " + new java.util.Date(f.lastModified()));
} else {
System.out.println(f.getName() + "라는 파일이 없습니다.");
}
}
}

Ex4 )

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.io.*;

public class Java {
public static void main(String[] ar){
//특정 폴더에서 확장자명 .java만 골라서 출력하도록한다
//ex ) 1 . Exam_01.java 2. Exam_02.java ..... 등등 이런식으로 출력
File f = new File("D:\\eclips\\workspace");
//정보를 얻고자하는 폴더에 대한 객체생성한다
//String[] files = f.list()
File[] files = f.listFiles();
//해당 폴더 내에 있는 모든 파일을 File클래스의 객체 배열로 획득한다
for(int i = 0, j = 0; i<files.length; i++){
if(files[i].getName().endWith(".java")){
//확장자명이 ".java" 인것만 검색하여 출력한다
System.out.println(j++ + 1 + ":" + files[i]getName());
}
}
}
}

Share