packagecom.imix.sftp;
importjava.io.File;
importjava.io.FileInputStream;
import Java.io.file not found exception;
importjava.io.FileOutputStream;
importjava.util.Properties;
importjava.util.Vector;
importcom.jcraft.jsch.Channel;
import com.j craft.jsch.channels FTP;
importcom.jcraft.jsch.JSch;
import com.j craft.jsch.jschexception;
importcom.jcraft.jsch.Session;
import com.j craft.jsch.sftp exception;
//*
公共类sftp {
//*
publicstaticvoidmain (stringdydkfdargs ) {
Stringhost='200.31.154.19 ';
输入=22;
Stringusername='root ';
Stringpassword='123456 ';
Stringdirectory='/home/imix/';
string uploadfile=' d :/ipconfig.txt ';
string downloadfile=' ipconfig.txt ';
string save file=' d :/ipconfig.txt ';
StringdeleteFile='ipconfig.txt ';
FTP.upload(directory,uploadFile,sftp );
FTP.download(directory,downloadFile,saveFile,sftp );
FTP.delete(directory,deleteFile,sftp );
try{
STP.CD (目录);
SFTP.mkdir(createfolder );
}catch(sftpexceptione ) {
e .打印任务跟踪(;
}finally{
try{
如果没有sesstion的disconnect,程序不会结束
sftp.getSession ().disconnect;
}catch(jschexceptione ) )
e .打印任务跟踪(;
}
sftp.disconnect (;
sftp.exit (;
}
}
//*
publicchannelsftpconnect (string host,intport,Stringusername,Stringpassword ) {
JSchjsch=newJSch (;
try{
sessionsshsession=jsch.getsession (username,host,port );
sshSession.setPassw
ord(password);Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
Channel channel = sshSession.openChannel("sftp");
channel.connect();
} 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());
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
public boolean download(String directory, String downloadFile, String saveFile, ChannelSftp sftp){
File file = new File(saveFile);
try {
sftp.cd(directory);
sftp.get(downloadFile, new FileOutputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (SftpException e) {
e.printStackTrace();
return false;
}
return true;
}
/**
public boolean delete(String directory, String deleteFile, ChannelSftp sftp){
try {
sftp.cd(directory);
sftp.rm(deleteFile);
} catch (SftpException e) {
e.printStackTrace();
return false;
}
return true;
}
/**
public Vector> listFiles(String directory, ChannelSftp sftp){
try {
return sftp.ls(directory);
} catch (SftpException e) {
e.printStackTrace();
}
return null;
}
}
感谢作者分享!