기존 Stream을 이용한 파일 Copy
import java.io.FileInputStream; import java.io.FileOutputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel;
public class CopyChannels { public static void main(String[] args) throws Exception {
String fromFileName = args[0]; String toFileName = args[1];
FileChannel in = new FileInputStream(fromFileName).getChannel(); FileChannel out = new FileOutputStream(toFileName).getChannel();
ByteBuffer buff = ByteBuffer.allocate(32 * 1024);
while (in.read(buff) > 0) { buff.flip(); out.write(buff); buff.clear(); }
in.close(); out.close(); }
} |
Buffer, Channel을 이용한 파일 Copy
Eg. 1
import java.io.FileInputStream; import java.io.FileOutputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel;
public class CopyChannels { public static void main(String[] args) throws Exception {
String fromFileName = args[0]; String toFileName = args[1];
FileChannel in = new FileInputStream(fromFileName).getChannel(); FileChannel out = new FileOutputStream(toFileName).getChannel();
ByteBuffer buff = ByteBuffer.allocate(32 * 1024);
while (in.read(buff) > 0) { buff.flip(); out.write(buff); buff.clear(); }
in.close(); out.close(); } }
|
Eg. 2
import java.io.FileInputStream; import java.io.FileOutputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel;
public class CopyChannels2 { public static void main(String[] args) throws Exception {
String fromFileName = args[0]; String toFileName = args[1];
FileChannel in = new FileInputStream(fromFileName).getChannel(); FileChannel out = new FileOutputStream(toFileName).getChannel();
ByteBuffer buff = ByteBuffer.allocateDirect(32 * 1024);
while (in.read(buff) > 0) { buff.flip(); out.write(buff); buff.clear(); }
in.close(); out.close(); } }
|
Eg. 3
import java.io.FileInputStream; import java.io.FileOutputStream; import java.nio.channels.FileChannel;
public class CopyChannels3 { public static void main(String[] args) throws Exception {
String fromFileName = args[0]; String toFileName = args[1];
FileChannel in = new FileInputStream(fromFileName).getChannel(); FileChannel out = new FileOutputStream(toFileName).getChannel();
in.transferTo(0, (int) in.size(), out);
in.close(); out.close(); } }
|
'Java > Input/Output Facilities' 카테고리의 다른 글
[NIO] 디렉토리 모니터링 API(WatchService) (0) | 2013.11.14 |
---|---|
[NIO] NIO의 기본 개념 (0) | 2013.11.14 |
Filter Stream과 Decorator 패턴 (0) | 2013.11.11 |
바이트 Stream과 문자 스트림 (0) | 2013.11.11 |
[바이트 스트림] 데이터 압축 및 해제 - GZIPOutputStream & GZIPInputStream 사용 (0) | 2013.02.11 |