import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
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;
public class SFTPUtils {
private static final Logger LOGGER =
LoggerFactory.getLogger(SFTPUtils.class);
public ChannelSftp connect(String host, int port, String username,
String password) {
ChannelSftp csftp = null;
JSch jsch = new JSch();
try {
Session sshSession = jsch.getSession(username, host,
port);
LOGGER.info("jsch session created, user={}",username);
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
LOGGER.info("session is connected.");
Channel channel = sshSession.openChannel("sftp");
channel.connect();
csftp = (ChannelSftp) channel;
LOGGER.info("connected to host:{}",host);
} catch (JSchException e) {
e.printStackTrace();
}
return csftp;
}
public boolean upload(String directory, String uploadFile,
ChannelSftp sftp) {
File file = new File(uploadFile);
try {
sftp.cd(directory);
sftp.put(new FileInputStream(file), file.getName());
LOGGER.info("upload file success, file:{}",uploadFile);
} catch (Exception e) {
LOGGER.error("upload file failed, file::{}",uploadFile);
e.printStackTrace();
return false;
}
return true;
}
public boolean upload(String directory, InputStream in,String
fileName, ChannelSftp sftp) {
try {
sftp.cd(directory);
sftp.put(in, fileName);
LOGGER.info("upload file success, file:{}",fileName);
} catch (Exception e) {
LOGGER.error("upload file failed, file::{}",fileName);
e.printStackTrace();
return false;
}
return true;
}
//
public static void main(String[] args) {
//
//
SFTPUtils ftp = new SFTPUtils();
//
String host = "10.201.128.125";
//
int port =22;
//
String username = "mysftp";
//
String password = "mysftp";
//
String directory = "./upload";
//
String uploadFile = "d:/20160719043248.xml";
//
ChannelSftp sftp = ftp.connect(host, port, username,
password);
//
ftp.upload(directory, uploadFile, sftp);
//
try {
//
//
如果没有sesstion的disconnect,程序不会退出
//
sftp.getSession().disconnect();
//
} catch (JSchException e) {
//
e.printStackTrace();
//
}
//
sftp.disconnect();
//
sftp.exit();
//
}
}
可能遇到的问题:
问题描述:服务器上能够看到这个上传的文件,但是文件的大小为0kb,Eclipse
Debug跟踪问题报错代码为put方法。
问题原因:服务器的使用空间为100%,无法再存储内容。
解决方案:清理服务器上的文件,释放空间。
4: Failure
at
com.jcraft.jsch.ChannelSftp.throwStatusError(ChannelSftp.java:2491)
at
com.jcraft.jsch.ChannelSftp.checkStatus(ChannelSftp.java:2141)
at
com.jcraft.jsch.ChannelSftp._put(ChannelSftp.java:612)
at com.jcraft.jsch.ChannelSftp.put(ChannelSftp.java:480)
at com.jcraft.jsch.ChannelSftp.put(ChannelSftp.java:439)
at
com.bailian.member.job.utils.SFTPUtils.upload(SFTPUtils.java:89)
加载中,请稍候......