FPT文件上传
作者:互联网
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;
public class SftpUtil {
static Session sshSession = null;
/**
* 获取ChannelSftp
*/
public static ChannelSftp getConnectIP(String host, String sOnlineSftpPort, String username, String password) {
int port = 0;
if (!("".equals(sOnlineSftpPort)) && null != sOnlineSftpPort) {
port = Integer.parseInt(sOnlineSftpPort);
}
ChannelSftp sftp = null;
try {
JSch jsch = new JSch();
jsch.getSession(username, host, port);
sshSession = jsch.getSession(username, host, port);
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
Channel channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
} catch (Exception e) {
e.printStackTrace();
}
return sftp;
}
/**
* 上传
*/
public static void upload(String directory, String uploadFile, ChannelSftp sftp) {
try {
sftp.cd(directory);
File file = new File(uploadFile);
sftp.put(new FileInputStream(file), file.getName());
System.out.println(">>>>>sftp上传文件成功!>>>>>"+"本地文件"+uploadFile+"sftp上传到"+directory);
} catch (Exception e) {
System.out.println(">>>>>sftp上传文件失败!>>>>>");
e.printStackTrace();
} finally {
if (sftp.isConnected()) {
sshSession.disconnect();
sftp.disconnect();
}
}
}
/**
* 下载
*/
public static void download(String directory, String downloadFile, String saveFile, ChannelSftp sftp) {
try {
sftp.cd(directory);
File file = new File(saveFile);
sftp.get(downloadFile, new FileOutputStream(file));
} catch (Exception e) {
e.printStackTrace();
} finally {
if (sftp.isConnected()) {
sshSession.disconnect();
sftp.disconnect();
}
}
}
/**
* 删除
*/
public static void delete(String directory, String deleteFile, ChannelSftp sftp) {
try {
sftp.cd(directory);
sftp.rm(deleteFile);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (sftp.isConnected()) {
sshSession.disconnect();
sftp.disconnect();
}
}
}
}
标签:jsch,文件,String,ChannelSftp,sftp,FPT,sshSession,import,上传 来源: https://www.cnblogs.com/clazz/p/15829696.html