[java] 자바에서 압축 파일을 다른 위치에 복사하기
먼저, java.util.zip
패키지를 이용하여 원하는 디렉토리로부터 압축 파일을 읽고, 새로운 위치에 압축을 푼 후 파일을 복사할 것입니다.
import java.io.*;
import java.util.zip.*;
public class ZipFileCopy {
public static void main(String[] args) {
String sourceFilePath = "path_to_source_file.zip";
String destinationDirectory = "path_to_destination_directory";
try {
File sourceFile = new File(sourceFilePath);
File destinationDir = new File(destinationDirectory);
// Unzip the file
unzip(sourceFile, destinationDir);
// Copy the unzipped files to another directory
copyFiles(destinationDir, new File("new_location_path"));
} catch (IOException e) {
e.printStackTrace();
}
}
private static void unzip(File source, File destination) throws IOException {
byte[] buffer = new byte[1024];
ZipInputStream zis = new ZipInputStream(new FileInputStream(source));
ZipEntry zipEntry = zis.getNextEntry();
while (zipEntry != null) {
File newFile = newFile(destination, zipEntry);
if (zipEntry.isDirectory()) {
newFile.mkdirs();
} else {
new File(newFile.getParent()).mkdirs();
FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
}
zipEntry = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
}
private static void copyFiles(File source, File destination) throws IOException {
if (source.isDirectory()) {
if (!destination.exists()) {
destination.mkdir();
}
String[] files = source.list();
for (String file : files) {
copyFiles(new File(source, file), new File(destination, file));
}
} else {
InputStream in = new FileInputStream(source);
OutputStream out = new FileOutputStream(destination);
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.close();
}
}
private static File newFile(File destinationDir, ZipEntry zipEntry) throws IOException {
File destFile = new File(destinationDir, zipEntry.getName());
String destDirPath = destinationDir.getCanonicalPath();
String destFilePath = destFile.getCanonicalPath();
if (!destFilePath.startsWith(destDirPath + File.separator)) {
throw new IOException("Entry is outside of the target dir: " + zipEntry.getName());
}
return destFile;
}
}
위의 코드는 압축 파일을 다른 위치로 복사하는 방법을 구현한 예시입니다. 코드를 실행하면, 압축 파일의 내용이 지정된 위치로 복사됩니다.
참고 문헌:
- https://docs.oracle.com/javase/8/docs/api/java/util/zip/package-summary.html