Jsch-传输文件到Sftp上(Java)
此博客为了防止博主忘记自己的想法以及学过的东西,在项目中发现一个较为方便传输文件到Sftp上的方法:
- 利用Jsch,定义对应的sftp的相应信息,可以直接将文件传输到sftp上。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
public class JschConnectSftp {
public static final Logger LOGGER = LoggerFactory.getLogger(JschConnectSftp.class);
public JschChannel getChannel(){
return new JschChannel();
}
public static void main(String[] args){
String username = "atLoan";
String password = "atLoan";
String host = "192.168.3.29";
int port = 22;
String loaclFile = "F:\\opt\\ftp\\bail\\20180522\\IN\\compensatory_2018042204.dat";
String remoteFilePath = "dev/bail/test";
JschConnectSftp connectSftp = new JschConnectSftp();
JschChannel jschChannel = connectSftp.getChannel();
ChannelSftp sftp = null;
try {
JSch jSch = new JSch();
Session session = jSch.getSession(username, host, port);
session.setPassword(password);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setTimeout(50000);
session.connect();
LOGGER.info("----------Session connected.------------");
Channel channel = session.openChannel("sftp");
channel.connect();
LOGGER.info("Connected successfully to ftpHost = " + host + ",as ftpUserName = " + username
+ ", returning: " + channel);
sftp = (ChannelSftp)channel;
sftp.setFilenameEncoding("UTF-8");
} catch (Exception e) {
LOGGER.info("111111");
LOGGER.error("身份验证失败" + e);
e.printStackTrace();
}
String[] names = remoteFilePath.split("[\\\\/]");
try{
if(names != null || names.length > 0){
for(int i = 0; i < names.length; i ++){
if(names[i] != null || names[i].length() > 0){
try{
sftp.cd(names[i]);
}catch(SftpException e){
sftp.mkdir(names[i]);
sftp.cd(names[i]);
}
}
}
}
}catch(Exception e){
e.getMessage();
}
try {
File file = new File(loaclFile);
sftp.put(new FileInputStream(loaclFile), file.getName());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SftpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(sftp.isConnected()){
try {
sftp.disconnect();
sftp.getSession().disconnect();
sftp.exit();
} catch (JSchException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}