[NIO] Stream 파일복사 vs Buffer/Channel 파일복사
기존 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(); } }
|