자바 학습 노트 - File I/O - java. nio. file. Path (Jdk 7) 와 java. io. File 비교

8488 단어 자바jdk7path
더 읽 기
Path 류 는 jdk 7 에 새로 추 가 된 특성 중 하나 로 자바. io. File 류 를 대체 합 니 다.
이 클래스 가 추 가 된 이 유 는 java. io. File 클래스 에 많은 결함 이 있 기 때 문 입 니 다.
 
1. java. io. File 클래스 에서 많은 방법 이 실 패 했 을 때 이상 처리 가 없 거나 이상 을 던 집 니 다. 예 를 들 어:
             
 public boolean delete() {
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkDelete(path);
        }
        return fs.delete(this);
    }

 java. io. File. delete () 방법 은 불 값 지시 가 성공 하거나 실 패 했 지만 실패 원인 이 없습니다.java. nio. file. Files. delete (경로):
 
 
public static void delete(Path path) throws IOException {
        provider(path).delete(path);
    }

 이 방법 은 NoSuchFileException, Directory NotEmpty Exception, IOException, Security Exception 등 파일 을 삭제 하 는 데 실 패 했 을 때 이상 에 따라 실패 원인 을 찾 을 수 있 습 니 다.
 
예 를 들 면:
 
package io.path;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class DeleteFile {

    public static void main(String[] args) throws IOException {
        Path path = Paths.get("H://afile");//This path does not exsit in file system.
        Files.delete(path);
    }
}

 실행 결과:
 
Exception in thread "main"java.nio.file.NoSuchFileException: H:\afile
at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:79)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:102)
at sun.nio.fs.WindowsFileSystemProvider.implDelete(WindowsFileSystemProvider.java:268)
at sun.nio.fs.AbstractFileSystemProvider.delete(AbstractFileSystemProvider.java:103)
at java.nio.file.Files.delete(Files.java:1077)
at io.path.DeleteFile.main(DeleteFile.java:12)
 
2. java. io. File. rename (File file) 방법 이 서로 다른 플랫폼 에서 실 행 될 때 문제 가 있 을 수 있 습 니 다. 이 방법 은 한 파일 시스템 에서 다른 파일 시스템 으로 파일 을 옮 길 수 없습니다. 이 방법 은 원자 적 인 것 도 아 닙 니 다. 매개 변수 가 지정 한 파일 이름 이 이미 존재 한다 면 이 방법 은 실 패 했 을 수도 있 습 니 다.
 
package io.path;

import java.io.File;
import java.io.IOException;
import java.nio.file.CopyOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class FileRename {

    /**
     * Expected Result: rename beforeRename1.txt to rename1.txt; beforeRename1.txt disappears; and the content of
     * rename1.txt is the same with beforeRename1.txt
     */
    public static void rename1() {

        File file = new File("D:\\360  \\javase\\src\\io\\beforeRename1.txt");// The content of beforeRename1.txt is a
                                                                              // string
                                                                              // with value "1111"

        File destinationfile1 = new File("D:\\360  \\javase\\src\\io\\rename1.txt");// rename1.txt has already
                                                                                    // existed. and the content is null.
        file.renameTo(destinationfile1);
    }

    /**
     * Expected Result: rename beforeRename2.txt to rename2.txt ;beforeRename2.txt disappears; and the content of
     * rename2.txt is the same with beforeRename2.txt,that is "2222"
     */
    public static void rename2() {

        File file = new File("D:\\360  \\javase\\src\\io\\beforeRename2.txt");// The content of beforeRename2.txt is a
                                                                              // string
                                                                              // with value "2222"

        File destinationfile2 = new File("D:\\360  \\javase\\src\\io\\rename2.txt");// rename2.txt does not exist.
        file.renameTo(destinationfile2);
    }

    
    /**
     * Expected Result: rename beforeRename3.txt to rename3.txt ;beforeRename3.txt disappears; and the content of
     * rename3.txt is the same with beforeRename3.txt ,that is "3333"
     */
    public static void rename3() throws IOException {
        Path path = Paths.get("D:\\360  \\javase\\src\\io\\beforeRename3.txt");// The content of beforeRename3.txt is a
                                                                               // string with value of "3333"

        Path pathRename = Paths.get("D:\\360  \\javase\\src\\io\\rename3.txt");// rename3.txt has already existed,and
                                                                               // the content is null.

        Files.move(path, pathRename, StandardCopyOption.REPLACE_EXISTING);
    }

    public static void main(String[] args) throws IOException {
//        rename1();
//        rename2();
        rename3();
    }
}

 
위의 클래스 에서 실 행 된 후에 beforeRename 1. txt 가 아직도 있 고 rename 1. txt 의 파일 내용 도 미터 가 바 뀌 었 으 며, beforeRename 2. txt 파일 은 rename 2. txt 로 이름 이 바 뀌 었 으 며, rename 2. txt 의 내용 은 beforeRename 2. txt 의 내용 과 마찬가지 로 '2222' 로 이름 이 바 뀌 었 다.그러나 자바. nio. Files. move (Path source, Path target, CopyOption... options) 를 사용 하면 rename 3 이 존재 하 더 라 도 beforeRename3. txt 를 성공 적 으로 rename3. txt 로 이름 을 바 꿀 수 있 습 니 다.
 
 
3. 파일 속성 관련 읽 기
File 클래스 에서 파일 속성 을 읽 는 것 은 하나의 방법 으로 속성 값 을 되 돌려 줍 니 다. 여러 속성 을 한 번 에 되 돌려 주 는 방법 이 없어 서 파일 속성 에 접근 할 때 효율 적 인 문 제 를 일 으 킵 니 다.
그러나 jkd 7 에 추 가 된 api 에 서 는 파일 속성 을 대량으로 읽 을 수 있 고 파일 의 더 자세 한 속성 에 접근 할 수 있 습 니 다.
package io.path;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Map;

public class FileAttribute {

    public static void main(String[] args) throws IOException {
        // ==============Get attribute by File=========================
        File file = new File("D:\\360  \\javase\\src\\io\\path.txt");
        System.out.println("isDirectory:" + file.isDirectory());
        System.out.println("isHidden:" + file.isHidden());
        System.out.println("canRead:" + file.canRead());
        System.out.println("canWrite:" + file.canWrite());
        System.out.println("lastModified:" + file.lastModified());
        System.out.println("length:" + file.length());

        // ==============Get attribute by Path=========================

        Path path = Paths.get("D:\\360  \\javase\\src\\io\\path.txt");
        readAttributes(path, "*", LinkOption.NOFOLLOW_LINKS);
        System.out.println(Files.getOwner(path, LinkOption.NOFOLLOW_LINKS).getName());

        BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class,
                LinkOption.NOFOLLOW_LINKS);
        System.out.println(attributes.fileKey());
        System.out.println(attributes.isOther());
    }

    /**
     * 
     * @param path
     * @param attributes
     * @param linkOption
     * @throws IOException
     */
    public static void readAttributes(Path path, String attributes, LinkOption... linkOption) throws IOException {
        Map map = Files.readAttributes(path, attributes, linkOption);
        for (String s : map.keySet()) {
            System.out.println(s + ":" + map.get(s));
        }
    }

}

 
이상 을 제외 하고 file. list () 와 같은 다른 문제 가 있 습 니 다.방법 은 비교적 큰 디 렉 터 리 를 처리 할 때 효율 이 매우 낮 지만 왜 효율 이 낮 습 니까?자바. nio. file 은 어떻게 최적화 되 었 습 니까?잘 모 르 겠 어 요.
 

좋은 웹페이지 즐겨찾기