Java NIO AsynchronousFileChannel 비동기 읽 기 및 쓰기 파일
5420 단어 자바nioAsynchronousFileChannel
1.AsynchronousFileChannel 만 들 기
정적 방법 open()을 통 해 AsynchronousFileChannel 을 만 들 수 있 습 니 다.
Path path = Paths.get("data/test.xml");
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
open()방법의 첫 번 째 매개 변 수 는 Path 인 스 턴 스 입 니 다.이 인 스 턴 스 는 Asynchronous FileChannel 과 연 결 된 파일 을 가리 키 고 있 습 니 다.
두 번 째 인 자 는 하나 이상 의 열 린 옵션 입 니 다.Asynchronous FileChannel 은 기본 파일 에 대해 어떤 작업 을 수행 하 는 지 알려 줍 니 다.이 예제 에서 저 희 는 StandardOpenOption.READ 를 사 용 했 습 니 다.이것 은 파일 을 열 어 읽 는 것 을 의미 합 니 다.
2.데이터 읽 기
두 가지 방식 으로 AsynchronousFileChannel 에서 데 이 터 를 읽 을 수 있 습 니 다.
3.Future 를 통 해 데이터 읽 기
AsynchronousFileChannel 에서 데 이 터 를 읽 는 첫 번 째 방법 은 read()방법 을 호출 하 는 것 입 니 다.이 방법 은 Future 로 돌아 갑 니 다.
Future operation = fileChannel.read(buffer, 0);
이 버 전의 read()방법 은 ByteBuffer 를 첫 번 째 매개 변수 로 합 니 다.AsynchronousFileChannel 에서 읽 은 데 이 터 는 이 ByteBuffer 에 읽 힙 니 다.두 번 째 매개 변 수 는 파일 에서 읽 기 시작 할 바이트 위치 입 니 다.
읽 기 작업 이 완료 되 지 않 았 더 라 도 read()방법 은 즉시 돌아 갑 니 다.read()방법 으로 되 돌아 오 는 Future 인 스 턴 스 의 isDone()방법 을 호출 하여 읽 기 작업 이 언제 끝 났 는 지 확인 할 수 있 습 니 다.
예시:
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
ByteBuffer buffer = ByteBuffer.allocate(1024);
long position = 0;
Future operation = fileChannel.read(buffer, position);
while(!operation.isDone());
buffer.flip();
byte[] data = new byte[buffer.limit()];
buffer.get(data);
System.out.println(new String(data));
buffer.clear();
이 예제 에 서 는 Asynchronous FileChannel 을 만 든 다음 ByteBuffer 를 만 들 고 이 를 매개 변수 로 read()방법 에 전달 하 며 위 치 를 0 으로 설정 합 니 다.read()를 호출 한 후,이 예제 가 돌아 오 는 Future 의 isDone()방법 이 true 로 돌아 올 때 까지 반복 적 으로 실 행 됩 니 다.물론 CPU 에 효과 적 인 사용 은 아 닙 니 다.-하지만 읽 기 작업 이 끝 날 때 까지 어떤 방식 으로 기 다 려 야 합 니 다.
읽 기 작업 이 완료 되면 데 이 터 는 ByteBuffer 에서 읽 힌 다음 String 에서 읽 히 고 System.out 에 인쇄 됩 니 다.
4.Complete Handler 를 통 해 데 이 터 를 읽 기
AsynchronousFileChannel 에서 데 이 터 를 읽 는 두 번 째 방법 은 CompletionHandler 를 매개 변수 로 하 는 read()방법 버 전 을 호출 하 는 것 입 니 다.
fileChannel.read(buffer, position, buffer, new CompletionHandler() {
@Override
public void completed(Integer result, ByteBuffer attachment) {
System.out.println("result = " + result);
attachment.flip();
byte[] data = new byte[attachment.limit()];
attachment.get(data);
System.out.println(new String(data));
attachment.clear();
}
@Override
public void failed(Throwable exc, ByteBuffer attachment) {
}
});
읽 기 작업 이 완료 되면 CompletionHandler 의 completed()방법 을 호출 합 니 다.방법 첫 번 째 매개 변 수 는 몇 바이트 가 읽 혔 는 지 를 나타 내 고 두 번 째 매개 변 수 는 read 읽 기 데이터 의 버퍼 입 니 다.
읽 기 작업 이 실패 하면 CompletionHandler 를 호출 하 는 failed()방법 으로 변 경 됩 니 다.
5.데이터 쓰기
읽 는 것 처럼 두 가지 방식 으로 데 이 터 를 Asynchronous FileChannel 에 쓸 수 있 습 니 다.
6.Future 를 통 해 데 이 터 를 기록 합 니 다.
AsynchronousFileChannel 도 데 이 터 를 비동기 로 기록 할 수 있 습 니 다:
Path path = Paths.get("data/test-write.txt");
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE);
ByteBuffer buffer = ByteBuffer.allocate(1024);
long position = 0;
buffer.put("test data".getBytes());
buffer.flip();
Future operation = fileChannel.write(buffer, position);
buffer.clear();
while(!operation.isDone());
System.out.println("Write done");
우선,쓰기 모드 로 Asynchronous FileChannel 을 엽 니 다.그리고 ByteBuffer 를 만 들 고 데 이 터 를 기록 합 니 다.그리고 ByteBuffer 의 데 이 터 를 파일 에 기록 합 니 다.마지막 으로 이 예제 에 서 는 기록 작업 이 언제 끝 나 는 지 보기 위해 되 돌아 오 는 Future 를 검사 합 니 다.
이 코드 가 발효 되 기 전에 파일 이 이미 존재 해 야 합 니 다.파일 이 존재 하지 않 으 면 write()방법 은 java.nio.file.NoSuchFileException 을 던 집 니 다.
경로 가 가리 키 는 파일 이 존재 하 는 지 확인 하려 면 다음 코드 를 사용 하 십시오.
if(!Files.exists(path)){
Files.createFile(path);
}
7.Complete Handler 를 통 해 데 이 터 를 기록 합 니 다.
또한 CompletionHandler 를 사용 하여 AsynchronousFileChannel 에 데 이 터 를 기록 하여 언제 끝 날 지 알려 줄 수 있 습 니 다.
Path path = Paths.get("data/test-write.txt");
if(!Files.exists(path)){
Files.createFile(path);
}
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE);
ByteBuffer buffer = ByteBuffer.allocate(1024);
long position = 0;
buffer.put("test data".getBytes());
buffer.flip();
fileChannel.write(buffer, position, buffer, new CompletionHandler() {
@Override
public void completed(Integer result, ByteBuffer attachment) {
System.out.println("bytes written: " + result);
}
@Override
public void failed(Throwable exc, ByteBuffer attachment) {
System.out.println("Write failed");
exc.printStackTrace();
}
});
쓰기 작업 이 완료 되면 CompletionHandler 의 completed()방법 을 호출 합 니 다.어떤 이유 로 기록 에 실패 하면 failed()방법 을 사용 합 니 다.
원본 주소: https://www.zhblog.net/go/java/tutorial/java-nio-asynchronous-filechannel?t=630
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.