거꾸로 바라본 세상
반응형

1. 파일채널 생성과 닫기



(1)  파일 채널 생성


- FileChannel은 정적 메소드인 open() 을 호출하여 사용하거나 IO의 FileInputStream, FileOutputStream의 getChannel() 메소드를 호출하여 사용할 수 있다.


1-1. open() 을이용한 파일생성


FileChannel fileChannel = FileChannel.open(Path path, OpenOption ... options);



ex)

FileChannel fileChannel = FileChannel.open(Paths.get("c://Temp/file.txt"), StandardOpenOption.READ);


Paths은 파일의 경로를 지정하는 것이고 , OpenOptions은 StandardOpenOption의 열거 상수를 이용하여 열기 옵션을 설정 할 수 있다.

 

StandardOpenOption 표



 열거상수

 설명 

 READ

 읽기전용 파일 열기

 WRITE

 쓰기전용 파일 열기

 CREATE

 파일이 없다면 새 파일을 생성 

 CREATE_NEW

 새 파일을 만들며, 이미 파일이 존재하면 예외와 함께 실패한다.

 APPEND

 파일 끝에 데이터를 추가한다(WRITE나 CREATE와 함께 사용가능)

 DELETE_ON_CLOSE

 스트림을 닫을 때 파일을 삭제한다.(임시파일을 삭제할때 이용)

 TRUNCATE_EXISTING

 파일을 0바이트로 잘라낸다(WRITE 옵션과 함께사용)


이런식으로 옵션을 여러개를 지정할 수 있다.


FileChannel fileChannel = FileChannel.open(Paths.get("c://Temp/file.txt"), StandardOpenOption.CREATE, StandardOpenOption.READ);



1-2. getChannel()을 이용한 파일 생성


- IO파일을 스트림을 생성 후  getChannel 메소드를 가져온다.


FileInputStream fis = new FileInputStream("c://temp/file.txt");

FileChannel fileChannel2 = fis.getChannel();



(2) 파일 종료


fileChannel.close();



2. 파일 읽기와 쓰기



2-1. 파일 쓰기


- 파일에 바이트를 쓰려면 FileChannel의 write()메소드를 호출하여 사용한다.

매개 값은 ByteBuffer를 이용하면되는데 파일에 쓰여지는 바이트는 ByteBuffer의 position부터 limit까지 이다.

position이 0이고 limit가 capacity와 동일하면 ByteBuffer 의 모든 바이트가 파일에 쓰여진다.

리턴값은 파일에 쓰여진 바이트 수



int byteCnt = fileChannel.write(ByteBuffer src);



ex)



String data= "hello world";


//파일 버퍼 생성

ByteBuffer buffer = ByteBuffer.allocateDirect(data.length());

Charset charset = Charset.forName("UTF-8");

buffer = charset.encode(data);


//파일 쓰기

int byteCnt = fileChannel.write(buffer);


//파일 종료

fileChannel.close();



2-2. 파일 읽기 


- 파일 읽기는 FileChannel의 read() 메소드를 이용하면 된다.

매개값은 ByteBuffer를 이용하면되고 파일에서 읽혀지는 바이트는 ByteBuffer의 position부터 이며 position이 0이면 ByteBuffer의 처 바이트부터 저장된다.  리턴 값은 ByteBuffer로 읽혀진 바이트의 수 만큼이며, 한 번 읽을 수 있는 최대 바이트 수는 ByteBuffer의 capacity까지이며 더이상 읽을 바이트가 없다면 -1을 리턴한다.


int byteCnt = fileChannel.read(ByteBuffer src);


ex)


FileChannel fileChannels = FileChannel.open(Paths.get("c://Temp/file.txt"), StandardOpenOption.READ);

ByteBuffer buffers = ByteBuffer.allocateDirect(100);

Charset charsets = Charset.forName("UTF-8");

data = "";

byteCnt = 0;

while(true) 

{

byteCnt = fileChannels.read(buffers);

if(byteCnt == -1) break;

buffers.flip();

data += charsets.decode(buffers).toString();

buffers.clear();

}

fileChannels.close();

System.out.println("file :"+ data);




3. 파일 복사


- 첫번째 source매개 값은 원본 파일의 Path을 지정해주고 두번째 target은 타겟 파일의 Path을 지정해주면된다.

세번 째는 StandardCopyOption 열거 상수를 목적에 맞게 나열해준다.


Path targetPath = Files.copy(Path source, Path target, CopyOption... option);




EX)


Path from = Paths.get("c:/temp/file.txt");

Path to = Paths.get("c:/temp/fileEx.txt");

Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING);




StandardCopyOption 표


 열거 상수 

 설명

 REPLACE_EXISTING

 타겟 파일이 존재하면 대체 

 COPY_ATTRIBUTES

 파일의 속성까지도 복사 

 NOFOLLOW_LINKS

 링크 파일일 경우 링크 파일만 복사하구 링크된 파일은 복사하지 않는다. 





















반응형

'Language > Java' 카테고리의 다른 글

java final 키워드  (0) 2016.08.11
쓰레드  (0) 2016.05.25
달력만들기  (0) 2016.03.25
Java 줄바꿈 처리  (0) 2016.03.07
SocketAddress 클래스와 NetworkInterface 클래스  (0) 2015.12.17
profile

거꾸로 바라본 세상

@란지에。

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!