import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class FTPUnzipExample {
public static void main(String[] args) {
String server = "your_server_address";
int port = 21;
String user = "your_username";
String pass = "your_password";
unzipFromFTP(server, port, user, pass);
}
public static void unzipFromFTP(String server, int port, String user, String pass) {
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
// 检查连接响应
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
System.out.println("Failed to connect to the FTP server.");
return;
}
ftpClient.login(user, pass);
// 获取要解压的 ZIP 文件
String zipFileName = "your_zip_file_name";
// 读取 ZIP 文件内容到字节数组
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (!ftpClient.retrieveFile(zipFileName, baos)) {
System.out.println("Failed to retrieve the ZIP file.");
return;
}
byte[] zipData = baos.toByteArray();
// 解压
unzip(ftpClient, new ByteArrayInputStream(zipData), new File(zipFileName).getParent());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void unzip(FTPClient ftpClient, InputStream inputStream, String destinationFolder) throws IOException {
ZipInputStream zipInputStream = new ZipInputStream(inputStream);
ZipEntry entry;
try {
while ((entry = zipInputStream.getNextEntry())!= null) {
String entryName = entry.getName();
String outputPath = destinationFolder + File.separator + entryName;
if (entry.isDirectory()) {
try {
ftpClient.makeDirectory(outputPath);
} catch (IOException e) {
System.out.println("Failed to create directory: " + outputPath + ", Error: " + e.getMessage());
}
} else {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
try {
while ((len = zipInputStream.read(buffer)) > 0) {
baos.write(buffer, 0, len);
}
} catch (IOException e) {
System.out.println("Failed to read from the ZIP entry: " + entryName + ", Error: " + e.getMessage());
}
byte[] content = baos.toByteArray();
BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(ftpClient.storeFileStream(outputPath));
bos.write(content);
} catch (IOException e) {
System.out.println("Failed to write to the FTP server for: " + outputPath + ", Error: " + e.getMessage());
} finally {
if (bos!= null) {
bos.close();
}
}
}
zipInputStream.closeEntry();
}
} catch (IOException e) {
System.out.println("Error occurred during unzipping: " + e.getMessage());
} finally {
zipInputStream.close();
}
}
}