#相关导入
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
public boolean getRemoteFileBySftp(String server, int port, String user, String password, String localpath,
String remotepath,String fileName, String okFileName) throws Exception{
boolean flag = false;
ChannelSftp sftp = null;
Channel channel = null;
Session sshSession = null;
InputStream is = null;
FileOutputStream fos = null;
try {
JSch jsch = new JSch();
jsch.getSession(user, server, port);
sshSession = jsch.getSession(user, server, port);
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
sftp.lcd(localpath);
sftp.cd(remotepath);
Vector<?> v = sftp.ls(remotepath);
for (Object item : v) {
LsEntry entry = (LsEntry) item;
if (entry.getFilename().equals(okFileName)) {
flag = true;
break;
}
}
if (flag) {
Path p = Paths.get(localpath, fileName);
is = sftp.get(fileName);
File downfile = new File(p.toString());
fos = new FileOutputStream(downfile);
copyInputStream(is, fos);
} else {
return flag;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeOutPutStream(fos);
closeInPutStream(is);
closeChannel(sftp);
closeChannel(channel);
closeSession(sshSession);
}
return flag;
}