자바 NIO 파일 입출력 샘플

자바 NIO 파일 입출력 샘플


FileChannel 파일에 쓰기와 읽기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import java.io.*;
import java.nio.*;
import java.nio.channels.*;

//FileChannel클래스를 사용하기 위해 import한다.
class mefile {
public static void main(String[] args) throws Exception {
String s = "Hello! getJAVA..안녕!! 겟자바..";
// 버퍼에 문자열 s를 담기 위해 바이트 배열을 바꾼다.
byte[] by = s.getBytes();
// 버퍼 생성
ByteBuffer buf = ByteBuffer.allocate(by.length);
// 바이트배열을 버퍼에 넣는다.
buf.put(by);
// 버퍼의 위치(position)는 0으로 limit와 capacity값과 같게 설정한다.
buf.clear();
// FileOutputStream 객체를 생성
FileOutputStream f_out = new FileOutputStream("a2.txt");
// getChannel()를 호출해서 FileChannel객체를 얻는다.
FileChannel out = f_out.getChannel();
// 파일에 버퍼의 내용을 쓴다.
out.write(buf);
// 채널을 닫는다. 이때 스트림도 닫힌다.
out.close();
// FileInputStream 객체 생성
FileInputStream f_in = new FileInputStream("a2.txt");
// getChannel()를 호출해서 FileChannel객체를 얻는다.
FileChannel in = f_in.getChannel();
// 바이트 버퍼 생성. 이때 버퍼의 크기는 현재 파일의 크기만큼 만든다.
// 파일의 크기는 리턴하는 size()는 long형을 리턴하므로 int형으로 캐스팅한다.
ByteBuffer buf2 = ByteBuffer.allocate((int) in.size());
// 파일을 내용을 읽어 버퍼에 담는다.
in.read(buf2);
// array()로 버퍼의 내용을 바이트 배열로 바꾼다.
byte buffer[] = buf2.array();
// 스트링으로 변환-->한글이 깨지지 않도록 하기 위해 한다.
String a = new String(buffer);
// 출력한다.
System.out.println(a);
}
}
Share