상세 컨텐츠

본문 제목

기초 ( File클래스 )

프로그래밍/JAVA

by 라제폰 2009. 1. 23. 16:54

본문

기초 ( File클래스 )

 

파일경로 이름을 나타내며 정보 추출 및 대응하는 실제 화일에 대한 조작 연산을 제공

파일의 내용을 입출력할 수 있는 메소드는 제공되지 않는다.

 

★ 상수:

static final String separator

- 실행중인 플랫폼에서의 화일경로 이름내의 디렉토리 구분자. (윈 \, 유닉스 /)

- file.separotor 시스템 포르퍼티 값으로 초기화 된다.

static final char separatorChar = File.separator.charAt(0)

 

static final String pathSeparator

- 실행중인 플랫폼에서의 파일 경로 이름 리스트의 구분자. ( 윈 ; 유닉스 : )

- path.separator 시스템 프로퍼티 값으로 초기화 된다.

 

static final char pathSeparotorChar = File.pathSeperator.char

 

★ 생성자 

new File ( String path )

new File ( String dir, String name)

new File ( File dir , String name )

 

★ 파일 경로 이름데 대한 정보 추출

String path : 경로 이름 자체

String name : 경로 이름 중 마지막 파일이름 부분

String parent : 경로 이름중 디렉토리 경로 이름 부분 없으면 null

File parentFile

boolean isAbsolute()

String absolutePath

: 절대 경로 이름을 반환 현재의 작업 디렉토리("user.directory" 시스템 프로퍼티 값) 이 상대 경로 이름을 연결한 절대 경로 이름을 반환.

String canonicalPath

: 표준 경로이름 . 일반적으로, 절대 경로 이름과 유사하며 플랫폼에 따라 부가적으로 대소분자 변환을 통하여 가장 적당한 이름으로 변환하여 반환

URL toURL()

 

★ 파일속성

boolean exists() : 해당파일이 실제존재 true

boolean isFile() : 해당파일이 실제존재하고 , 보통의 파일이면

boolean isDirectory : 파일이 실제로 존재하고, 디렉토리이면 true

boolean canRead()

boolean canWrite()

boolean isHidden()

long length() : 해당 파일의 크기(바이트 개수)

long lastModified()

: 파일이 마지막으로 수정된 시각을 나타내나, 그 값이 작으면 수정 시각이 이르다는 것만의미

( 윈두으즈 솔라리스 Jdk버젼은 System.currentTimeMillis()와 같은 기준시각)

boolean setReadOnly()

boolean setLastModified(long time)

 

★ 파일접근 ( 조작이 성공하였을 경우 true 반환)

File[] File.listRoots() : 시스템의 루트 디렉토리 목록

String list() : 이 디렉토리내의 파일 이름 목록

File[] listFiles() :

File[] listFiles(FileFilter filter)  : 파일이름

File[] listFiles( FileNameFilter filter)

boolean mkdir() : 디렉토리 생성

boolean mkdirs() : 경로상의 모든 디렉토리 생성

boolean renameTo( File dest ) : 파일이름을 dest로 변경

boolean delete() : 삭제

deleteOnExit() throws IOException

File File.createTempFile(String  prefix, String suffix, File directory=null) throws IOException

: 임시 파일 생성

boolean createNewFile() throws IOException

: 이 이름의 파일이 없는경우 크기 0의 파일 생성.

deleteOnExit()와 함께 파일 locking프로토콜을 구현하는데 사용할 수있다.

 

import java.io.*;
public class FileTest1 {
        FileInputStream fis;
        byte[] buf;
 
        public FileTest1(String fileName) throws FileNotFoundException {
                fis=new FileInputStream(fileName);
                buf=new byte[1024];
        }
        public void readUntilEnd() {
                FileOutputStream fos=null;
                try {
                        fos=new FileOutputStream("복사본");
                        for (int i; (i=fis.read(buf))!=-1; ) {
                                System.out.write(buf, 0, i);
                                fos.write(buf, 0, i);
                        }
                } catch(IOException ioe) {
                        System.out.println("스트림에 이상이 있음 : "+ioe.getMessage());
                } finally {
                        try {
                                fis.close();
                        } catch(IOException ioe2) {
                        }
                        try{
                                fos.close();
                        } catch(IOException ioe2) {
                        }
                }
        }
        public static void main(String[] args) {
                if (args.length<1) {
                        System.out.println("사용법 : java FileTest1 파일이름");
                        System.exit(1);
                }
                try {
                        FileTest1 test=new FileTest1(args[0]);
                        test.readUntilEnd();
                } catch(FileNotFoundException fnfe) {
                        System.out.println(args[0]+" 파일을 찾을 수 없습니다.");
                }
        }
}

 

import java.io.*;

class FileTest
{   public static void main( String[] args )
    {  File file1 = new File("sample"+File.separator+"file1.txt");
       File file2 = new File("sample",  "file1.txt");
       System.out.println(file1.getPath());    // sample\file1.txt
       System.out.println(file2.getPath());    // sample\file1.txt
       System.out.println(file1.toString());   // sample\file1.txt
       System.out.println(file1.getName());    // file1.txt
       System.out.println(file1.getParent());  // sample
       System.out.println(file1.getAbsolutePath());
                               // C:\example\io\sample\file1.txt
       System.out.println(file1.isAbsolute()); // false
       System.out.println(file1.exists());     // true
       System.out.println(file1.isFile());     // true
       System.out.println(file1.isDirectory());// false
       System.out.println(file1.canRead());    // true
       System.out.println(file1.canWrite());   // true
       System.out.println(file1.length());     // 34
       System.out.println(file1.lastModified()); // 856163661000
       String[] listing = new File("sample").list();
       for( int i = 0; i < listing.length; ++i)
           System.out.println(listing[i]);     // file1.txt
                                               // file2.txt
                                               // file3.txt
    }
}

 

import java.io.*;
import java.util.Date;
import java.text.*;


class Dir
{
    public static void main( String[] args )
    {
        try
        {   if ( args.length == 0 )
            {   list( System.getProperty( "user.dir" ) );
            }
            else if ( args[0].equals("/d")
                      && System.getProperty("os.name").startsWith("Windows") )
                listDrives();
            else
                list( args[0] );
        } catch( IOException e )
        {   System.err.println( "오류: 장치가 준비되지 않았습니다." );
        }
    }

    static void listDrives()
    {
        for( char drv = 'A'; drv <= 'Z'; ++drv )
            if ( new File(drv + ":").exists() )
                System.out.print( drv + ": " );
        System.out.println();
    }

    static void list( String path ) throws IOException
    {
        // 디렉토리 경로이름 조정 (JDK 1.1.x 버그에 대한 해결책)
        if ( System.getProperty("os.name").startsWith("Windows")
             && path.length() == 3 && path.charAt(2) == '\\' )
            path += ".";

        File f = new File( path );
        File dir;

        if ( ! f.exists() )
        {   System.out.println( "디렉토리/화일이 없습니다." );
        }
        else if ( f.isDirectory() )
        {   System.out.println( " 디렉토리 " + f.getCanonicalPath() );
            if ( ! f.canRead() )
            {   System.out.println( "디렉토리 내용을 읽을 수 있는 권한이 없습니다..");
                return;
            }
            System.out.println();
            String[] listing = f.list();
            for( int i = 0; i < listing.length; i++ )
                printFileInfo( new File(f, listing[i]) );
        }
        else
        {   String parent = new File(f.getCanonicalPath()).getParent();
            System.out.println( " 디렉토리 " + parent );
            System.out.println();
            printFileInfo(f);
        }
    }

    static MessageFormat fmt = new MessageFormat(
            "{0,date,yy-MM-dd}  {0,time,HH:mm} {1}" );
    static DecimalFormat subFmt = new DecimalFormat( "#,##0" );

    static void printFileInfo(File f)
    {   Object sizeCol = f.isDirectory() ?
            "<DIR>      "
            : padToWidth( subFmt.format(f.length()), 11 );
        System.out.println( sizeCol + "  " +
                            fmt.format( new Object[] {
                                new Date(f.lastModified()), f.getName() } ) );
              // 주의: lastModified()의 문서화되지 않은 특징에 의존함
    }

    static String padToWidth(String s, int width)
    {   int len = s.getBytes().length;
        if ( len >= width )
            return s;
        char padding[] = new char[width - len];
        for( int i = 0; i < padding.length; i++ )
            padding[i] = ' ';
        return new String(padding) + s;
    }
}

java Dir /d

C: D: E: F: G: ....

java Dir  현재디렉토리 출력

java Dir c: = java Dir c:\

java Dir c:\windows

 

import java.io.*;
public class FileTest2 implements FileFilter { 
        File file;
        public FileTest2(String fileName) {
                file=new File(fileName);
        }
        public void test() throws Exception {
                if (!file.exists()) {
                        System.out.println("파일이 존재하지 않습니다. "+file);
                        System.exit(1);
                }
 
                System.out.println("절대경로 : "+file.getAbsolutePath());
                System.out.println("공식경로 : "+file.getCanonicalPath());
                System.out.println("파일크기 : "+file.length());
                System.out.println("만든날짜 : "+new java.util.Date(file.lastModified()));
                System.out.println("네트워크경로 : "+file.toURL());
 
                if (file.isDirectory()) {
                        File[] list=file.listFiles(this); // listFiles(FileFilter filter)
 
                        System.out.println("\n디렉토리 안의 내용 ---");
                        for (int i=0; i<list.length; i++) {
                                System.out.print(list[i].getName());
                                System.out.print("\t");
                                System.out.println(list[i].length());
                        }
                }
                System.out.println("\n파일시스템");
                File[] roots=File.listRoots();
                for (int i=0; i<roots.length; i++) {
                        System.out.println(roots[i].getPath());
                }
        }
        public boolean accept(File path) {
                return path.isFile();
        }
 
        public static void main(String[] args) throws Exception {
                if (args.length<1) {
                        System.out.println("사용법 : java FileTest2 파일이름");
                        System.exit(1);
                }
                FileTest2 test=new FileTest2(args[0]);
                test.test();
        }
}

java FileTest c:/

FileFilter를 구현하고 있는데 public boolean accept(File path) 라는 메소드를 가지고 있다.

이메소드는 디렉토리가 아닌 파일들만 골라내도록 한다.

FileInputStream 과는 다르게 File객체는 실제하지 않는 파일에 대해서도 만들어질수 있다.

createNew() 메소드를 사용하면 크기가 0인 파일에 대해서도 만들어 질수있다.

listFile(FileFilter filter)메소드 : 그냥 listFile()메소드를 쓰면 그 디렉토리안의 모든 파일들의 리스트가 File[]객체로 넘어온다. 하지만 FileFilter객체를 이용하면 원하는 파일들의 list만 얻을수 있다.

FileFilter객체로 this 객체로 지정했는데 FileTest클래스는 Filefilter인터페이스를 구현하고 있다는 사실을 기억하자 this는 FileTest인 동시에 곧 FileFilter이기도 한것입니다.

기타 API : 임시파일을 만들수 있는 createTempFile() , deleteOnExit()메소드도 흥미있는 메소드이며 java.lang.Comparable 인터페이스의 유산인 compareTo(Object obj), compareTo(File file)

 

RandomAccessFile : 무작위 접근 파일

 

FileInputStream과 FileOutputStream은 단방향이라는 성질때문에 파일의 여기저기를 누비면서 사용할수 없다.

 

DataInut            DataOutput

    |                          |

-------------------------

  RandomAccessFile

 

파일의 입출력의 위치를 임으로 변경하여 입출력 할 수 있다.

파일로의 입력과 출력을 동시에 제공한다.

 

InputStream, OutputStream의 하위 클래스가 이니므로, 필터링 스트림 클래스를 쓸 수 없다.

 

★ 생성자

new RandomAccessFile( String name, String mode) throws FileNotFoundException

new RandomAccessFile ( File file, String mode ) throws IOException

mode는 "r"(읽기전용) 혹은 "rw"이다

 

★ 메소드

long getFilePointer() : 파일의 현재 접근 위치 반환

long seek() : 파일의 현재 접근 위치 변경

long length()

int read()

int read( byte[] buf, int off=0, len= buf.length

close()

 

import java.io.*;

class RandomAccessFileTest
{   public static void main( String[] args )
        throws IOException
    {   RandomAccessFile f = new RandomAccessFile(args[0], "rw");
        System.out.println(f.length());
        System.out.print((char)f.read());
        System.out.print((char)f.read());
        System.out.println(f.getFilePointer());
        f.seek(1);
        System.out.print((char)f.read());
        f.write('x');
        f.seek(f.length());
        f.write('y');
        System.out.print(f.length());
        f.close(); System.out.close();
    }
}

 

import java.io.*;  
  public class RandomAccessFileTest {
        public static void main(String[] args) throws IOException {
                File imsiFile=File.createTempFile("imsi", ".tmp");
                imsiFile.deleteOnExit();
                FileOutputStream fos=new FileOutputStream(imsiFile);
                for (int i=0; i<=100; i++) {
                        fos.write(i);
                }
                fos.close();
  
                RandomAccessFile raf=new RandomAccessFile(imsiFile, "rw");
                for (int i=0; i<=100; i+=10) {
                        raf.seek(i); // 바이트를 찾는다.
                        System.out.print(raf.readByte());
                        System.out.print(" ");
                }
        }
}

0 10 20 30 40 50 60 70 80

seek(i) 메소드가 파일을 쓰거나 읽는 곳의 위치를 움직이게 한다. 이위치를 파일 포인터라고 하는데 getFilePointer()를 통해 현재 파일포인터의 위치를 알수 있다.

 

1번째 인자로 키워드를 주고 2번째 인자로 파일이름을 주면, 키워드를 포함하는 모든 행을 찾아서 파일 이름과 행번호 및 해당행을 출력하는 프로그램을 짜라.

2번째 인자로 디렉토리 이름을 주면, 하위 디렉토리를 포함하여 모든 파일에 대해서 주어진 키워드를 포함하는 행을 찾아라

import java.io.*;
class Grep {
    public static void main(String args[]) {
        search(args[0], new File(args[1]));  
   }
   public static void search(String target, File f) {
      try {
          if(f.isFile()) {
             BufferedReader in = new BufferedReader(new FileReader(f));
             int lineCount = 1;
             for(String line; (line=in.readLine())!=null; lineCount++) {
                if((line.indexOf(target))!=-1) {
                   System.out.println(f.getPath()+":"+lineCount+":"+line);
                }
             }  
          }else if(f.isDirectory()) {
             String[] fileNames = f.list();
             for(int i=0; i < fileNames.length; i++) {
                   search(target, new File(fileNames[i]));
             }
         }
      } catch (CharConversionException e) {
           System.out.println(f.getPath()+" 는 이진 파일입니다.");
      }  catch (Exception e) {
           e.printStackTrace();
      }
   }
}

java Grep import Grep.java

java Grep import .


관련글 더보기