java.io를 사용하지 않고 filechannel 받기* (순수한 NIO 사용)
문제
최근에 나는 이것에 대해 의견을 받았습니다 대답 내가 멀리 있어야한다 java.io
"Pure 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를 사용하지 않고 파일을 읽기위한 다른 NIO 클래스 (FileInputStream
)?
편집하다:
Java 6 (또는 이전)
해결책
그만큼 Filechannel의 Javadoc 말 :
이 클래스는 기존 파일을 여는 방법을 정의하거나 새 파일을 만들기위한 방법을 정의하지 않습니다. 이러한 방법은 향후 릴리스에 추가 될 수 있습니다. 이 릴리스에서 파일 채널은 해당 객체의 getChannel 메서드를 호출하여 기존 FileInputStream, FileOutputStream 또는 RandomAccessFile 객체에서 얻을 수 있으며,이 파일은 동일한 기본 파일에 연결된 파일 채널을 반환합니다.
즉, Java 1.6을 사용하면 FileChannel
오래된 것을 사용하지 않고 java.io
.
다른 팁
Java 6 만 있습니다 FileInputStream.getChannel()
, FileOutputStream.getChannel()
, 그리고 RandomAccessFile.getChannel()
Java 7이 있습니다 java.nio.channels.FileChannel.open(...)
그리고 java.nio.Files.newByteChannel(...)