引入的jar包:
<dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.55</version> </dependency>
工具类:
import java.io.IOException; import java.io.InputStream; import java.util.Properties; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.ChannelShell; import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session; public class FileUploadUtil { 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 void storeFile(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(); } } /** * 创建服务器连接 * * @param host * 主机 * @param user * 用户 * @param password * 密码 * @param waitSeconds * 等待秒数 * @return */ private static Session openSession(String host, String user, String password, int waitSeconds) { Session session = null; try { JSch jsch = new JSch(); 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(); } return session; } /** * 不作检查主机键值 * * @param session */ private static void noCheckHostKey(Session session) { Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); } /** * 连接shell * * @param session * session * @return {@link ChannelShell} */ private static ChannelShell 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"); } return channel; } /** * 连接sftp * * @param session * @return {@link ChannelSftp} */ private static ChannelSftp openChannelSftp(Session session) { ChannelSftp channel = null; try { channel = (ChannelSftp) session.openChannel("sftp"); channel.connect(); } catch (Exception e) { e.printStackTrace(); } return channel; } }