从sftp上下载到本地的zip文件是没问题的,用压缩工具打开能查看里面的文件,为什么就是读取不了呢?
java从sftp下载zip文件到本地磁盘代码:
import java.io.InputStream;
import java.util.Date;
import com.ibm.gbs.ai.portal.framework.util.DateUtils;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class FtpZipOption {
public static String ftpServer = "***";//有关机密不便给大家看,理解万岁!
public static int ftpPort = 22;
public static String ftpUserName = "***";
public static String ftpPassword = "***";
@SuppressWarnings({ "rawtypes", "resource" })
public static void main(String[] args) throws Exception {
Session session = null;
Channel channel = null;
JSch jsch = new JSch();
if(ftpPort <=0){
//连接服务器,采用默认端口
session = jsch.getSession(ftpUserName, ftpServer);
}else{
//采用指定的端口连接服务器
session = jsch.getSession(ftpUserName, ftpServer ,ftpPort);
}
//如果服务器连接不上,则抛出异常
if (session == null) {
throw new Exception("session is null");
}
//设置登陆主机的密码
session.setPassword(ftpPassword);//设置密码
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
//设置登陆超时时间
session.connect();
try {
//创建sftp通信通道
channel = (Channel) session.openChannel("sftp");
channel.connect();
ChannelSftp sftp = (ChannelSftp) channel;
//进入服务器指定的文件夹
sftp.cd("download/"+DateUtils.convert(DateUtils.convert(DateUtils.addDay(new Date(), -1)), "yyyyMMdd"));
String[] tt = sftp.ls("*.zip").get(0).toString().split(" ");
InputStream input = sftp.get(tt[tt.length-1]);
sftp.get("D:\hh", tt[tt.length-1]);
// ftp.openConnect();
/*if (ftp.createFile("/alipay/download/"+DateUtils.convert(DateUtils.convert(DateUtils.addDay(new Date(), -1)), "yyyyMMdd"))) {
ftp.uploadFile("/alipay/download/"+DateUtils.convert(DateUtils.convert(DateUtils.addDay(new Date(), -1)), "yyyyMMdd"),
"alipay_record_"+DateUtils.convert(DateUtils.convert(DateUtils.addDay(new Date(), -1)), "yyyyMMdd")+".zip",input);
}*/
input.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}finally{
session.disconnect();
channel.disconnect();
}
}
}
java读取从sftp上下载到本地的zip文件代码:
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import org.apache.commons.collections.CollectionUtils;
import com.ibm.gbs.ai.portal.framework.util.StringUtils;
public class testUtils {
@SuppressWarnings({ "resource", "unused" })
public static void main(String[] args) throws IOException {
// logger.info("进入下载。。。。");
String localFtp ="alipay_record_20150324.txt";
// FtpUtils ftp = new FtpUtils(Const.FTP_SERVER, Const.FTP_PROT, Const.FTP_USER_NAME, Const.FTP_PASSWORD);
// ftp.openConnect();
String productName = "商品名称";
String likeFileName = "财务明细.csv";
ZipFile zipFile = null;
byte[] buffer = new byte[1024];
// InputStream in = ftp.returnFileStream(new String(remoteFile, "gb2312"));
InputStream in = new BufferedInputStream(new FileInputStream("D:\hh\2088001502510167_20150325.zip"));
// CheckedInputStream csumi = new CheckedInputStream(in, new Adler32());
ZipInputStream zin = new ZipInputStream(in);
if (in != null) {
try {
ZipEntry zz = null;
List list = new ArrayList();
if (zin == null) {
return;
}else {
while ((zz = zin.getNextEntry()) != null) {//在这把报错了,错误是:“java.lang.IllegalArgumentException”,zin.getNextEntry()因为ZipInputStream对象zin中根本这个属性
if (zz.isDirectory()) {
return;
}else {
String name = zz.getName();
String [] names = name.split("_");
if (StringUtils.equals(names[names.length-1].trim(), likeFileName)) {
@SuppressWarnings("null")
final BufferedReader br = new BufferedReader(new InputStreamReader(zipFile.getInputStream(zz),"gb2312"));
String line;
while ((line = br.readLine()) != null) {
final StringTokenizer st = new StringTokenizer(line, "");
String [] temps = line.split(",");
if (temps.length < 9 || StringUtils.equals(productName, temps[8].trim())) {
continue;
}
final String rowInfo = st.nextToken();
list.add(rowInfo+"\n");
}
}
}
}
if (CollectionUtils.isNotEmpty(list)) {
for (int i = 0; i < list.size(); i++) {
buffer = list.get(i).getBytes();
}
ByteArrayInputStream input = new ByteArrayInputStream(buffer);
// String filePath = "/alipay/download/"+DateUtils.convert(DateUtils.convert(DateUtils.addDay(new Date(), -2)), "yyyyMMdd");
// ftp.uploadFile(filePath, localFtp, input);
input.close();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (zin != null) {
zin.close();
}
} catch (Exception e2) {
// logger.error("关闭流异常:"+e2.getMessage());
e2.printStackTrace();
}
}
}
// ftp.close();
// logger.info("下载结束!");
}
}
读取zip文件那段代码,我读取从其他地方下载下来的zip文件是OK的,但是读取从sftp上下载到本地的zip文件却不行。
你在下载zip文件的时候为什么不直接用download方法,zip的文件名字应该是有命名规范的吧?我才做的项目就是直接用的download方法下载zip文件,是正常的
给你提供一些代码,希望对你有些帮助
// 组装连接SFTP服务器需要的参数
Map sftpConstants = new HashMap();
sftpConstants.put("host", sysInfo.getSftpHost());
sftpConstants.put("user", sysInfo.getSftpUser());
sftpConstants.put("password", sysInfo.getSftpPassword());
String proxyHost = sysInfo.getSftpProxyHost();
String proxyPort = sysInfo.getSftpProxyPort();
if (null != proxyHost && !"".equals(proxyHost) && null != proxyPort && !"".equals(proxyPort)) {
sftpConstants.put("proxyHost", proxyHost);
sftpConstants.put("proxyPort", proxyPort);
}
//sftp文件夹目录
String remoteDir = sysInfo.getSftpDownloadPath() + DateUtil.getCur8Date();
//sftp上文件名字
String remoteFileName = "****_*****_" + DateUtil.getCur8Date() + ".zip";
//存放文件本地目录
String localDir = sysInfo.getMsgPath() + System.getProperty("file.separator") + "download" + System.getProperty("file.separator") + DateUtil.getCurDate("yyyy/yyyyMM/yyyyMMdd/");
String localZipFilePath = localDir + remoteFileName;
File localFileDir = new File(localDir);
if (!localFileDir.exists()) {
localFileDir.mkdirs();
if (!localFileDir.exists()) {
throw new AdapterException("本地目录不存在,且尝试创建失败!");
}
}
int connectCount = 1;
int maxConnectCount = 3;
ChannelSftp sftp = null;
// 最多循环尝试3次连接
while (connectCount <= maxConnectCount) {
try {
logger.info("第【{}】次尝试连接STFP服务器...", connectCount);
sftp = SftpUtil.connect(sftpConstants);
logger.info("SFTP连接成功.");
break;
} catch (Throwable t) {
sftp = null;
++connectCount;
logger.error("连接SFTP服务器发生异常:【{}】", t.getMessage());
continue;
}
}
if (null == sftp)
throw new AdapterException("SFTP服务器无法连接。");
// 下载文件
SftpUtil.download(sftp, remoteDir, remoteFileName, localDir);
logger.info("文件下载成功.");
// 断开SFTP服务器
if (sftp.isConnected()) {
SftpUtil.disconnect(sftp);
logger.info("断开与SFTP服务器的连接.");
}
// 解压zip文件
String newContFileName = ZipUtil.unzip4zhaocaibao(localZipFilePath);
时间久了忘记了,dowload方法是我之前封装的,也提供给你吧
package com.hxlife.adapter.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Map;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hxlife.adapter.exception.AdapterException;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.ProxyHTTP;
import com.jcraft.jsch.Session;
// TODO: 上传文件夹,下载文件夹,删除操作
public class SftpUtil {
private static final Logger logger = LoggerFactory.getLogger(SftpUtil.class);
private SftpUtil() {
}
/** 连接sftp服务器 */
public static ChannelSftp connect(Map<String, String> sftpConstants) {
ChannelSftp sftp = null;
try {
String host = sftpConstants.get("host");
String port = sftpConstants.get("port");
if (null == port)
port = "22";
String user = sftpConstants.get("user");
String password = sftpConstants.get("password");
String proxyHost = sftpConstants.get("proxyHost");
String proxyPort = sftpConstants.get("proxyPort");
String timeout = sftpConstants.get("timeout");
if (null == timeout)
timeout = "20000";
logger.info("SFTP服务器地址:【{}:{}】", host, port);
Session session = new JSch().getSession(user, host, Integer.parseInt(port));
if (null != password)
session.setPassword(password);
if (null != proxyHost && null != proxyPort) {
session.setProxy(new ProxyHTTP(proxyHost, Integer.parseInt(proxyPort)));
logger.info("使用代理服务器【{}:{}】连接sftp", proxyHost, proxyPort);
}
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setTimeout(Integer.parseInt(timeout));
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
logger.info("SFTP服务器连接成功.");
} catch (Throwable t) {
logger.error("SFTP服务器连接失败", t);
throw new AdapterException(t.getMessage());
}
return sftp;
}
/** 断开sftp服务器连接 */
public static void disconnect(ChannelSftp sftp) {
if (sftp != null && sftp.isConnected()) {
sftp.disconnect();
sftp = null;
logger.info("断开与SFTP服务器的连接");
}
}
/**
* 下载文件
* @param remoteDir 需要下载的文件在SFTP服务器上的目录位置
* @param remoteFileName 需要下载的文件名称
* @param localDir 本地存放路径
*/
public static void download(ChannelSftp sftp, String remoteDir, String remoteFileName, String localDir) {
try {
String saveFile = localDir + System.getProperty("file.separator") + remoteFileName;
File file = new File(saveFile);
sftp.cd(remoteDir);
sftp.get(remoteFileName, new FileOutputStream(file));
logger.info("【{}】下载成功", remoteFileName);
} catch (Throwable t) {
logger.error("文件下载失败!", t);
throw new AdapterException(t.getMessage());
}
}
/**
* 上传文件
* @param remoteDir 上传的目录
* @param localFileName 要上传的文件
*/
public static void upload(ChannelSftp sftp, String remoteDir, String localFileName) {
try {
sftp.cd(remoteDir);
File file = new File(localFileName);
sftp.put(new FileInputStream(file), file.getName());
logger.info("【{}】上传成功", localFileName);
} catch (Throwable t) {
logger.error("文件上传失败!", t);
throw new AdapterException(t.getMessage());
}
}
}