Javaでフォルダ内のすべてのファイルを圧縮する方法は何ですか?
Javaでは、ZipOutputStreamクラスを使用してフォルダ内のすべてのファイルを圧縮することができます。以下はその例です:
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipFolder {
public static void main(String[] args) {
File folderToZip = new File("path/to/folder");
File zipFile = new File("path/to/output.zip");
try {
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
zipFolder(folderToZip, folderToZip.getName(), zos);
zos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void zipFolder(File folder, String parentFolderName, ZipOutputStream zos) throws IOException {
for (File file : folder.listFiles()) {
if (file.isDirectory()) {
zipFolder(file, parentFolderName + "/" + file.getName(), zos);
} else {
FileInputStream fis = new FileInputStream(file);
ZipEntry zipEntry = new ZipEntry(parentFolderName + "/" + file.getName());
zos.putNextEntry(zipEntry);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
fis.close();
zos.closeEntry();
}
}
}
}
上記の例では、まず圧縮したいフォルダのパスと出力先のzipファイルのパスを指定する必要があります。次に、zipFolderメソッドを使用して、フォルダ内のすべてのファイルを再帰的に走査し、それらをZipOutputStreamに追加します。最後に、ストリームを閉じて圧縮プロセスを完了します。