반응형
자바에서 파일을 복사하는 코드이다. JDK 1.4 이상에부터는 java.nio.* 패키지를 사용하며 더 빠른 IO 작업을 할 수 있다.
1. JDK 1.4 이전에서 IO 패키지 이용
import java.io.*;
public static void copyFile(String source, String target) throws IOException {
FileInputStream fis = new FileInputStream(source);
FileOutputStream fos = new FileOutputStream(target);
try {
byte[] buf = new byte[1024];
int i = 0;
while ((i = fis.read(buf)) != -1) {
fos.write(buf, 0, i);
}
} catch (IOException e) {
throw e;
} finally {
if (fis != null)
fis.close();
if (fos != null)
fos.close();
}
} |
2. JDK 1.4 이상에서 NIO 패키지 이용 (더 빠름)
import java.io.*;
import java.nio.channels.*;
public static void copyFile(String source, String target) throws IOException {
FileChannel inChannel = new FileInputStream(source).getChannel();
FileChannel outChannel = new FileOutputStream(target).getChannel();
try {
// magic number for Windows, 64Mb - 32Kb
int maxCount = (64 * 1024 * 1024) - (32 * 1024);
long size = inChannel.size();
long position = 0;
while (position < size) {
position += inChannel.transferTo(position, maxCount, outChannel);
}
} catch (IOException e) {
throw e;
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
} |