81,092
社区成员
发帖
与我相关
我的任务
分享
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.Selectors;
import org.apache.commons.vfs2.impl.*;
import org.apache.commons.vfs2.provider.local.DefaultLocalFileProvider;
import org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;
import com.jcraft.jsch.*;
public class SFTPTest {
public static void main(String[] args) {
startFTP("192.168.64.37","username","1234","/","C:/Temp/", "FILE_20170308.CSV");
}
public static boolean startFTP(String serverAddress,String userId,String password,String remoteDirectory ,String localDirectory, String fileToDownload){
StandardFileSystemManager manager = new StandardFileSystemManager();
try {
//Initializes the file manager
manager.init();
//Setup our SFTP configuration
FileSystemOptions opts = new FileSystemOptions();
SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");
SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);
//Create the SFTP URI using the host name, userid, password, remote path and file name
String sftpUri = "sftp://" + userId + ":" + password + "@" + serverAddress + "/" +
remoteDirectory + fileToDownload;
// Create local file object
String filepath = localDirectory + fileToDownload;
File file = new File(filepath);
FileObject localFile = manager.resolveFile(file.getAbsolutePath());
System.out.println("manager.resolveFile localFile successful");
// Create remote file object
FileObject remoteFile = manager.resolveFile(sftpUri, opts);
System.out.println("manager.resolveFile remoteFile successful");
// Copy local file to sftp server
localFile.copyFrom(remoteFile, Selectors.SELECT_SELF);
System.out.println("File download successful");
}
catch (Exception ex) {
ex.printStackTrace();
return false;
}
finally {
manager.close();
}
return true;
}
}