import java.io.*;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
public class demo {
public static void main(String[] args) {
//传递时间
fullSyncData("xx.xx.xxx.xxx","8080","ceshi","ceshi");
}
public static void fullSyncData(String ip, String port,String ftpUserName,String ftpPassword) {
try {
FTPClient ftpClient = ftpConnection(ip, port, ftpUserName, ftpPassword);
String remoteFile = "full/";
String localFile ="D://";
downLoadFTP(ftpClient, remoteFile, localFile);
close(ftpClient);
} catch (IOException e) {
e.printStackTrace();
}
}
public static boolean downLoadFTP(FTPClient ftp, String filePath,
String downPath) {
// 下载是否成功的标志,默认失败
boolean flag = false;
try {
// 跳转到文件目录
ftp.changeWorkingDirectory(filePath);
// 获取目录下文件集合
ftp.enterLocalPassiveMode();
FTPFile[] files = ftp.listFiles();
for (FTPFile file : files) {
File downFile = new File(downPath + File.separator
+ file.getName());
OutputStream out = new FileOutputStream(downFile);
// 绑定输出流下载文件,需要设置编码集,不然可能出现文件为空的情况
flag = ftp.retrieveFile(new String(file.getName().getBytes("UTF-8"), "ISO-8859-1"), out);
out.flush();
out.close();
if (flag) {
log.info("下载成功");
readZipFile(downPath + "\\" + file.getName());
} else {
log.error("下载失败");
}
}
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
public static void close(FTPClient ftpClient) throws IOException {
if (ftpClient != null && ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
}
public void readZipFile(String file) throws Exception {
ZipFile zf = new ZipFile(file);
Enumeration zipEnum = zf.entries();
InputStream in = new BufferedInputStream(new FileInputStream(file));
ZipInputStream zin = new ZipInputStream(in);
while (zipEnum.hasMoreElements()) {
ZipEntry ze = (ZipEntry) zipEnum.nextElement();
if (!ze.isDirectory()) {
System.err.println("file:" + ze.getName() + "\nsize:" + ze.getSize() + "bytes\nCompressedSize:" + ze.getCompressedSize());
if (ze.getSize() > 0) {
BufferedReader br = new BufferedReader(
new InputStreamReader(zf.getInputStream(ze)));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}
}
}
zin.closeEntry();
}
}
连接FTP服务器,然后下载zip文件并读取文件内容
最新推荐文章于 2022-11-14 12:40:45 发布