摘要:JAVA SFTP
參考網頁:
http://ziyouxf.iteye.com/blog/506161
jar檔下載點
public class SFTP {
public String error_message ="";
public boolean is_error =false;
/**
* 連接sftp服務器 * @param host主機 * @param port端口 * @param username用戶名 * @param password密碼 * @return
*/
public ChannelSftp connect(String host, int port, String username, String password) {
ChannelSftp sftp = null;
try {
JSch jsch = new JSch();
jsch.getSession(username, host, port);
Session sshSession = jsch.getSession(username, host, port);
System.out.println("Session created. ");
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
System.out.println("Session connected.");
System.out.println("Opening Channel.");
Channel channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
System.out.println("Connected to " + host + ".");
is_error = false;
} catch (Exception e) {
this.error_message = OtherTool.getTool().getErrorStackMessage(e);
this.is_error = true;
e.printStackTrace();
}
return sftp;
}
/**
* 上傳文件 * @param directory上傳的目錄 * @param uploadFile要上傳的文件 * @param sftp
*/
public void upload(String directory, String uploadFile, ChannelSftp sftp) {
try {
this.error_message = "";
sftp.cd(directory);
File file = new File(uploadFile);
FileInputStream fileInputStream = new FileInputStream(file);
sftp.put(new FileInputStream(file), file.getName());
fileInputStream.close();
fileInputStream=null;
file =null;
is_error = false;
} catch (Exception e) {
this.error_message =e.toString();
this.is_error = true;
e.printStackTrace();
}
}
/**
* 下載文件 * @param directory下載目錄 * @param downloadFile下載的文件 * @param saveFile存在本地的路徑 * @param sftp
*/
public void download(String directory, String downloadFile, String saveFile, ChannelSftp sftp) {
try {
this.error_message = "";
sftp.cd(directory);
File file = new File(saveFile);
FileOutputStream fileOutputStream =new FileOutputStream(file);
sftp.get(downloadFile, fileOutputStream );
fileOutputStream.close();
fileOutputStream=null;
file =null;
is_error = false;
} catch (Exception e) {
this.error_message = e.toString();
this.is_error = true;
e.printStackTrace();
}
}
/**
* 刪除文件 * @param directory要刪除文件所在目錄 * @param deleteFile要刪除的文件 * @param sftp
*/
public void delete(String directory, String deleteFile, ChannelSftp sftp) {
try {
this.error_message = "";
sftp.cd(directory);
sftp.rm(deleteFile);
is_error = false;
} catch (Exception e) {
this.error_message = e.toString();
this.is_error = true;
e.printStackTrace();
}
}
/**
* 列出目錄下的文件 * @param directory要列出的目錄 * @param sftp * @return * @throws SftpException
*/
public Vector listFiles(String directory, ChannelSftp sftp) throws SftpException {
return sftp.ls(directory);
}
}