파일과 디렉토리 접근

1. File 객체로 작업하기

<1> File 객체의 개념

   ▣ 파일이나 디렉토리에 대한 경로 또는 참조를 추상화한 객체

<2> File 객체의 용도

   ▣ 물리적 파일 시스템에 대해 캡슐화한 경로명을 확인하고

       실제의 파일이나 디렉토리와 대응되는지 알아볼 때

   ▣ 파일 스트림 객체를 생성하고자 할 때

2.  File 객체 생성하기

   ▣ File 객체를 생성하는 데에는 네 개의 생성자를 사용할 수 있다

       ① File myFile = new File("C:/j2SDK 1.4.0/src/java/io/File.java");

       ② File myDir = new File("C:/j2SDK 1.4.0/src/java/io"); // 부모 디렉토리

File myFile = new File(myDir, "File.java");  // 파일의 경로

       ③ File myFile = new File("C:/j2SDK 1.4.0/src/java/io" ,"File.java");

       ④ File remoteFile = new File(new URI(http://p2p.wrox.com/java));

   ▣ 경로에 대한 이식성을 고려

       * 경로 이름을 만드는 것은 시스템에 의존적이지만

          File 클래스의 separator 변수를 사용함으로써

          좀더 시스템에 독립적으로 myFile에 대한 경로를 지정 가능

3. File 객체를 확인하고 테스트하기

<1> File 객체에 대한 정보를 얻을 수 있는 메서드

   ▣ getName()

   ▣ getPath()

   ▣ isAbsolute()

   ▣ getParent()

   ▣ toString()

   ▣ hashCode()

   ▣ equals()

<2> File 객체가 참조하는 파일이나 디렉토리를 테스트하기 위한 메서드

   ▣ exist() //참조하는 파일 또는 디렉토리가 존재하는가

   ▣ isDirectory() //디렉토리를 참조하는가

   ▣ isFile() //파일을 참조하는가

   ▣ isHidden() //숨김 속성이 있는 파일을 참조하는가

   ▣ canRead() //파일 또는 디렉토리가 읽을 권한이 있는가

   ▣ canWrite() //파일 또는 디렉토리가 쓰기 권한이 있는가

   ▣ getAbsolutePath() //절대경로 리턴

   ▣ getAbsoluteFile() //절대경로를 포함한 File 객체 리턴

   ▣ (예) 파일 테스트하기

(소스코드)

import java.io.File;

public class TryFile { 
public static void main(String[] args) {

// 디렉토리를 참조하는 객체 생성 
File myDir = new File("C:/JAVA/Chapter09"); 
System.out.println(myDir + (myDir.isDirectory() ? " is" : " is not") 
                       + " a directory.");

// 파일을 참조하는 객체 생성 
File myFile = new File(myDir, "TryFile3.java"); 
System.out.println(myFile + (myFile.exists() ? " does" : " does not") 
                       + " exist"); 
System.out.println(myFile + (myFile.isFile() ? " is" : " is not") 
                       + " a file."); 
System.out.println(myFile + (myFile.isHidden() ? " is" : " is not") 
                       + " hidden"); 
System.out.println("You can" + (myFile.canRead() ? " " : "not ") 
                       + "read " + myFile); 
System.out.println("You can" + (myFile.canWrite() ? " " : "not ") 
                       + "write " + myFile); 
return; 
  } 
}


 

<3> 존재하는 파일 또는 디렉토리에 대해 더 많은 정보를 제공해주는 메서드

   ▣ list() //디렉토리 내의 파일 이름과 하위 디렉토리의 이름을 담고 있는 String 배열 리턴

   ▣ listFiles() //디렉토리 내의 파일과 하부 디렉토리에 대응되는 File 객체 배열 리턴

   ▣ length() //파일의 길이

   ▣ lastModified() //마지막 수정시각

   ▣ (예) 더 많은 정보 얻기

(소스코드)

import java.io.File;
import java.util.Date;   // Date 클래스를 사용하기 위해 포함시킴

public class TryFile2 {
public static void main(String[] args) {

// 디렉토리를 참조하는 객체 생성
File myDir = new File("C:/JAVA/Chapter09");
System.out.println(myDir.getAbsolutePath()
                       + (myDir.isDirectory() ? " is " : " is not ")
                       + "a directory");
System.out.println("The parent of " + myDir.getName() + " is "
                       + myDir.getParent());

// 디렉토리 내의 파일 리스트를 얻어옴
File[] contents = myDir.listFiles();

// 파일 리스트를 출력
if (contents != null) {
System.out.println("\nThe " + contents.length
                         + " items in the directory " + myDir.getName()
                         + " are:");
for (int i = 0; i < contents.length; i++) {
System.out
          .println(contents[i] + " is a "
                   + (contents[i].isDirectory() ? "directory" : "file")
                   + " last modified "
                   + new Date(contents[i].lastModified()));
      }
    } else {
System.out.println(myDir.getName() + " is not a directory");
    }

System.exit(0);
  }
}


 

<4> 파일 리스트 필터링

   ▣ list()와 listFiles() 메서드는 파일 리스트를 필터링하는 인자를 받도록 오버로드 되어 있다

   ▣ list() 메서드의 인자는 FilenameFilter 타입의 변수여야 하지만,

   ▣ listFiles() 메서드는 FilenameFilter와FileFilter 두 가지를 모두 사용할 수 있다

   ▣ (예) FilenameFilter  인터페이스 사용하기

(소스코드)

1) TryFile3  클래스

import java.io.File;

import java.io.FilenameFilter; 
import java.util.Date;   // Date 클래스를 사용하기 위해 포함시킴

public class TryFile3 { 
public static void main(String[] args) {

// 디렉토리를 참조하는 객체 생성 
File myDir = new File("C:/JAVA/Chapter09"); 
System.out.println(myDir.getAbsolutePath() 
                       + (myDir.isDirectory() ? " is " : " is not ") 
                       + "a directory"); 
System.out.println("The parent of " + myDir.getName() + " is " 
                       + myDir.getParent());

    // F로 시작하는 자바 소스 파일을 필터링하기 위한 필터 정의 
FilenameFilter select = new FileListFilter("F", "java");

// 디렉토리 내의 파일 리스트를 얻어옴 
File[] contents = myDir.listFiles(select);

// 파일 리스트를 출력 
if (contents != null) { 
System.out.println("\nThe " + contents.length 
                         + " items in the directory " + myDir.getName() 
                         + " are:"); 
for (int i = 0; i < contents.length; i++) { 
System.out 
          .println(contents[i] + " is a " 
                   + (contents[i].isDirectory() ? "directory" : "file") 
                   + " last modified " 
                   + new Date(contents[i].lastModified())); 
      } 
    } else { 
System.out.println(myDir.getName() + " is not a directory"); 
    }

System.exit(0); 
  } 
}

2) FileListFilter  클래스

import java.io.File; 
import java.io.FilenameFilter;

public class FileListFilter implements FilenameFilter { 
private String name;        // 파일 이름 
private String extension;   // 파일 확장자

// 생성자 
public FileListFilter(String name, String extension) { 
this.name = name; 
this.extension = extension; 
  }

public boolean accept(File directory, String filename) { 
boolean fileOK = true;

// 필터링하기 위한 파일 이름이 설정되어 있으면 파일 이름을 확인함 
if (name != null) 
      fileOK &= filename.startsWith(name);

    // 필터링하기 위한 확장자가 설정되어 있으면 확장자를 검사함 
if (extension != null) 
      fileOK &= filename.endsWith('.' + extension);

return fileOK; 
  } 
}


 

4. 파일과 디렉토리를 생성하고 수정하기

   ▣ File 클래스에는 그 파일을 읽기 전용으로 만들거나 이름을 바꾸는 등 물리적인 파일에

       변화를 줄 수 있는 메서드가 있다.

       또한 파일 또는 디렉토리를 생성하거나 삭제할 수 있게 해주는 메서드들도 있다.

   ▣ renameTo(File path)

   ▣ setReadOnly()

   ▣ mkdir()

   ▣ mkdirs()

   ▣ createNewFile()

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

   ▣ createTempFile(String prefix, String suffix)

   ▣ delete()

   ▣ deleteOnExit()

5. 파일 출력 스트림 생성하기

   ▣ 디스크에 존재하는 물리적인 파일에 무언가 쓰고자 할 때

       FileOutputStream 객체를 사용할 수 있다

   ▣ FileOutputStream 객체의 다섯 개의 생성자

       * FileOutputStream(String filename)

       * FileOutputStream(String filename, boolean append)

       * FileOutputStream(File file)

       * FileOutputStream(File file, boolean append)

       * FileOutputStream(FileDescriptor desc)

6. 파일이 존재하는 것을 보장하기

   ▣ 파일이 존재하면 이 파일에 데이터를 덧붙이고 존재하지 않는 파일이면 생성하고자 할 때

       파일 출력 스트림을 생성해야하는데, 여기서 확인해야 할 것들이 있다.

   ▣ File 객체를 사용해서 실제로 디렉토리가 아니라 파일을 나타내고 있는지 확인한다.

       만일 파일이 아니라면 더 이상 진행하지 말고 오류 메시지를 출력해 주어야 한다.

   ▣ 그 파일이 존재하는지 확인하기 위해 File 객체를 사용한다. 파일이 존재하지 않는다면

       File 객체가 절대경로를 가지고 있는지 확인해야 한다.

       이것은 부모 디렉토리를 얻어오고 확인하는 데 사용된다.

   ▣ 부모 디렉토리에 대한 경로를 얻어오고 이것을 사용해서 다른 File 객체를 생성한다.

       부모 디렉토리가 존재하는지 확인하기 위해 새로운 File 객체를 사용한다.

       만약 존재하지 않는다면 File 객체의 mkdir() 메서드를 사용해서 새로 생성한다.

   ▣ (예) 파일이 존재하는 것을 보장하기

(소스코드)

import java.io.File; 
import java.io.FileOutputStream; 
import java.io.FileNotFoundException;

public class GuaranteeAFile { 
public static void main(String[] args) { 
String filename = "C:/Beg Java Stuff/Bonzo/Beanbag/myFile.txt"; 
File aFile = new File(filename);    // File 객체 생성

// 경로가 파일인지를 확인 
if (aFile.isDirectory()) {

// 오류 메세지 후에 종료함 
      // 여기에서 키보드로부터 입력을 받아 다시 시도하도록 할 수 있음 
System.out.println("The path " + aFile.getPath() 
                         + " does not specify a file. Program aborted."); 
System.exit(1); 
    }

  // 파일이 존재하지 않을 경우 
if (!aFile.isFile()) { 
// 부모 디렉토리를 확인 
      aFile = aFile.getAbsoluteFile(); 
File parentDir = new File(aFile.getParent()); 
if (!parentDir.exists()) {   // 필요하다면 디렉토리를 생성 
        parentDir.mkdirs(); 
      } 
    }

// 스트림에 대한 참조를 저장할 장소 
FileOutputStream outputFile = null; 
try {

// 데이터를 추가하는 데 사용될 스트림 생성 
      outputFile = new FileOutputStream(aFile, true); 
    } catch (FileNotFoundException e) { 
      e.printStackTrace(System.err); 
    } 
System.exit(0); 
  } 
}


 

7. 파일 덮어쓰는 것을 방지하기

   ▣ 이미 파일이 존재할 때 그 파일을 덮어쓰고 싶을 않을 때

       덮어쓰기를 막을 수 있는 방법이 있다.

       저장하려는 원래 이름을 어떠한 방법으로든 바꿔준다면

       그것이 덮어쓰기를 막을 수 있는 한 가지 방법이 될 수 있다.

   ▣ (예) 파일을 덮었는 것을 방지하기

(소스코드)

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;

public class AvoidOverwritingFile {
public static void main(String[] args) {
String filepath = "C:/Beg Java Stuff/myFile.txt";
File aFile = new File(filepath);
FileOutputStream outputFile = null;     // 스트림에 대한 참조를 저장할 장소
if (aFile.isFile()) {
File newFile = aFile;                 // 원래의 파일을 가지고 시작함

  // 유일한 이름이 될 때까지 파일 이름에 "_old"를 덧붙임
do {
String name = newFile.getName();    // 파일의 이름을 얻어옴
int period =
          name.indexOf('.');         // 확장자의 구분자를 찾음
        newFile = new File(newFile.getParent(),
                           name.substring(0, period) + "_old"
                           + name.substring(period));
      } while (newFile.exists());             // 이름이 바뀔 때까지 반복
      aFile.renameTo(newFile);              
    }

// 새로운 파일 생성
try {

// 데이터를 추가하기 위한 스트림 생성
      outputFile = new FileOutputStream(aFile);
System.out.println("myFile.txt output stream created");
    } catch (FileNotFoundException e) {
      e.printStackTrace(System.err);
    }
System.exit(0);
  }
}


 

8. FileDescriptor 객체

<1> FileDescriptor 객체

   ▣ FileOutputStream에는 FileDescriptor 타입의 객체를 리턴해주는 getFD() 메서드가 있다.

   ▣ 여기서 FileDescriptor는 물리적인 파일에 대한 현재의 연결을 나타내는 객체이다.

   ▣ 직접 FileDescriptor 객체를 생성할 수는 없고 파일 스트림을 나타내는 객체로부터

       getFD() 메서드를 호출해서 FileDescriptor 객체를 얻을 수 있다

   ▣ 스트림을 한번 닫고 나면 파일에 대한 연결이 끊어지므로 더 이상 FileDescriptor 객체를

       얻을 수 없다

<2> FileDescriptor 객체 사용

   ▣  표준 스트림에 대응되는 바이트나 문자 스트림을 만들고자 할 때 편리하게 사용할 수 있다

 

Tistory 태그: ,

'IT > Language' 카테고리의 다른 글

[javascript] 금액표시/숫자여부체크/replace  (0) 2008.09.20
[java] 날짜 구하기  (0) 2008.09.20
[java] 객체 풀의 동작 원리  (0) 2008.09.20
[JAVA] 문자열중에 한글체크 - getType  (0) 2008.09.20
javacore&heapdump  (0) 2008.09.19

+ Recent posts