importjava.io.IOException;importjava.io.InputStream;importjava.util.Properties;importcom.jcraft.jsch.ChannelSftp;importcom.jcraft.jsch.ChannelShell;importcom.jcraft.jsch.JSch;importcom.jcraft.jsch.Session;public classFileUploadUtil {private static final int DEFAULT_PORT = 22;//端口
private static final int DEF_WAIT_SECONDS = 30;//请求时间
private static String username = "*****";//用户名
private static String host = "192.168.195.129";//ip地址
private static String password = "*****";//密码//放在服务器的目标位置
private static String dstfilepath = "/home/huyanlon/harbinFile";public static voidstoreFile(String sourcefileName, InputStream inpustStream) {//sourcefileName 文件名称 inpustStream 文件流
Session session=openSession(host, username, password, DEF_WAIT_SECONDS);
ChannelShell openChannelShell=openChannelShell(session);
openChannelShell.setInputStream(System.in);
openChannelShell.setOutputStream(System.out);
ChannelSftp openChannelSftp=openChannelSftp(session);try{
openChannelSftp.put(inpustStream, dstfilepath+"/"+sourcefileName);//删除文件可用如下方法,进入某文件所在的目录后删除该文件//openChannelSftp.cd(dstfilepath);//openChannelSftp.rm(sourcefile);
} catch(Exception e) {
e.printStackTrace();
}
}/*** 创建服务器连接
*
*@paramhost
* 主机
*@paramuser
* 用户
*@parampassword
* 密码
*@paramwaitSeconds
* 等待秒数
*@return
*/
private static Session openSession(String host, String user, String password, intwaitSeconds) {
Session session= null;try{
JSch jsch= newJSch();
session=jsch.getSession(user, host, DEFAULT_PORT);
noCheckHostKey(session);
session.setPassword(password);//这个设置很重要,必须要设置等待时长为大于等于2分钟
session.connect(waitSeconds * 1000);if (!session.isConnected()) {throw new IOException("We can't connection to[" + host + "]");
}
}catch(Exception e) {
e.printStackTrace();
}returnsession;
}/*** 不作检查主机键值
*
*@paramsession*/
private static voidnoCheckHostKey(Session session) {
Properties config= newProperties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
}/*** 连接shell
*
*@paramsession
* session
*@return{@linkChannelShell}*/
private staticChannelShell openChannelShell(Session session) {
ChannelShell channel= null;try{
channel= (ChannelShell) session.openChannel("shell");
channel.setEnv("LANG", "en_US.UTF-8");
channel.setAgentForwarding(false);
channel.setPtySize(500, 500, 1000, 1000);
channel.connect();
}catch(Exception e) {
e.printStackTrace();
}if (channel == null) {throw new IllegalArgumentException("The channle init was wrong");
}returnchannel;
}/*** 连接sftp
*
*@paramsession
*@return{@linkChannelSftp}*/
private staticChannelSftp openChannelSftp(Session session) {
ChannelSftp channel= null;try{
channel= (ChannelSftp) session.openChannel("sftp");
channel.connect();
}catch(Exception e) {
e.printStackTrace();
}returnchannel;
}
}