2010-01-10 5 views
2

최근에이 answer에 "pure NIO"를 사용하려면 java.io에서 멀리 떨어져 있어야한다는 의견이있었습니다.
는 단순화 된 코드 (파일을 복사)되는이 :java.io. *을 사용하지 않고 FileChannel 가져 오기 (순수 NIO 사용)

private static void copy(File source, File destination) throws IOException { 
    long length = source.length(); 
    FileChannel input = new FileInputStream(source).getChannel(); 
    FileChannel output = new FileOutputStream(destination).getChannel(); 

    input.transferTo(0, length, output); 

    output.close(); 
    input.close(); 
} 

(코드 매우 단순화 : 제거 마지막으로-시도하고 루프)

내 질문 얻는 방법이다 FileChannel 또는 기타 java.io (FileInputStream)를 사용하지 않고 파일을 읽는 NIO 클래스?

편집 :
자바 6

답변

4

javadoc of FileChannel 말한다 (또는 전에 만) :

기존 파일을 여는하거나 새로 생성하는 방법을 정의하지 않습니다이 클래스; 이러한 방법은 향후 릴리스에서 추가 될 수 있습니다. 이 릴리스에서는 동일한 기본 파일에 연결된 파일 채널을 반환하는 해당 객체의 getChannel 메서드를 호출하여 기존 FileInputStream, FileOutputStream 또는 RandomAccessFile 객체에서 파일 채널을 가져올 수 있습니다.

즉, Java 1.6에서는 이전 java.io을 사용하지 않고 FileChannel을 얻을 수 없습니다.

4

자바 6 만 FileInputStream.getChannel()FileOutputStream.getChannel()을 가지고 있으며, RandomAccessFile.getChannel()

자바 7 java.nio.channels.FileChannel.open(...)java.nio.Files.newByteChannel(...)

있다
관련 문제