一、Java压缩zip代码:
public static Boolean picListToZip(List<String> mognoList, String ftpPath, String zipName) {
HashMap<Object, Object> hashMap = new HashMap<>();
//链接
JSch jsch = new JSch();
Session session = null;
ChannelSftp sftpChannel = null;
try {
session = jsch.getSession("用户名", "xxx.xxx.xxx.xxx", 端口号);
session.setConfig("StrictHostKeyChecking", "no");//使用带私钥的JSch来FTP文件
session.setPassword("密码");
session.connect(30000);
Channel channel = session.openChannel("sftp");
channel.connect();
sftpChannel = (ChannelSftp) channel;
//链接成功
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipName));
byte[] buff = new byte[1024];
//添加文件源
for (int i = 0; i < mognoList.size(); i++) {
FSObject fsObject = (MongoDBUtil.getObject("mongo桶", mognoList.get(i))); //从mongoDB中获取文件信息
InputStream is = fsObject.getInputstream();
zos.putNextEntry(new ZipEntry(fsObject.getName()));//会在压缩文件中建立名字为zipName的文件夹中建立fsObject.getName()文件
int len = 0;
while ((len = is.read(buff)) > 0) {
zos.write(buff, 0, len);
}
zos.closeEntry();
is.close();
}
zos.close();
FileInputStream in = new FileInputStream(new File(zipName)); // 转换为输入流
//切换到指定文件夹---线上操作
if (sftpChannel.ls(ftpPath) == null) {
log.info("如果文件夹不存在,则创建文件夹");
sftpChannel.mkdir(ftpPath);
}
sftpChannel.cd(ftpPath);
sftpChannel.put(in, zipName);
log.info("一次结束");
sftpChannel.exit();
} catch (Exception e) {
sftpChannel.exit();
session.disconnect();
e.printStackTrace();
return false;
}
return true;
}
二、使用时出现的异常问题:
java.util.zip.ZipException: duplicate entry: xxx文件
at java.util.zip.ZipOutputStream.putNextEntry(ZipOutputStream.java:215)
出现这种错误的原因是:打包的过程中,出现相同的文件名称
zos.putNextEntry(new ZipEntry(fsObject.getName()));//会在压缩文件中建立名字为zipName的文件夹中建立fsObject.getName()文件
参数 fsObject.getName() 存在相同的文件名称时,就会出现开头处的异常信息。