1.需求背景:跨服务器,将图片上传到新的服务器(图片服务器)保存
a.使用sftp的时候,经常报错ssh连接不对,换了jsch的jar进行开发、ftp工具类
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Properties;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelShell;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
/**
* FTP服务器工具类
*
*/
public class FTPUtils {
public static final String CHANNELTYPE_SFTP="sftp";
public static final String CHANNELTYPE_EXEC="exec";
private Session session;//会话
private Channel channel;//连接通道
private ChannelSftp sftp;// sftp操作类
private JSch jsch;
/*protected static String host=getLinuxParam()[0];
protected static String port=getLinuxParam()[1];
protected static String user=getLinuxParam()[2];
protected static String password=getLinuxParam()[3];*/
/*protected static String host="120.27.167.70";
protected static String port="6331";
protected static String user="ytyfemall";
protected static String password="ytyfemall";*/
protected static String host=ConfigManager.getString("file.host", "");;
protected static String port=ConfigManager.getString("file.port", "");;
protected static String user=ConfigManager.getString("file.user", "");;
protected static String password=ConfigManager.getString("file.password", "");;
private static String[] getLinuxParam(){
Properties props=new Properties();//读取文件类型创建对象。
try {
ClassLoader classLoader = FTPUtils.class.getClassLoader();// 读取属性文件
InputStream in = classLoader.getResourceAsStream("c");
props.load(in); /// 加载属性列表
if(in!=null){
in.close();
}
} catch (Exception e) {
System.out.println("Linux连接参数异常:"+e.getMessage());
}
String[] str={"","","",""};
str[0]=props.getProperty("file.host");
str[1]=props.getProperty("file.port");
str[2]=props.getProperty("file.user");
str[3]=props.getProperty("file.password");
return str;
}
/**
* 断开连接
*/
public static void closeConnect(Session session, Channel channel, ChannelSftp sftp){
if (null != sftp) {
sftp.disconnect();
sftp.exit();
sftp = null;
}
if (null != channel) {
channel.disconnect();