Uploading file on SFTP Server
import java.io.File; import org.apache.commons.vfs2.FileObject; import org.apache.commons.vfs2.FileSystemException; import org.apache.commons.vfs2.FileSystemOptions; import org.apache.commons.vfs2.Selectors; import org.apache.commons.vfs2.impl.StandardFileSystemManager; import org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder; public class SftpUploadFile { public static void main(String[] args) { String hostName = "localhost"; String username = "admin"; String password = "admin"; String localFilePath = "C:/myfile.txt"; String remoteFilePath = "/Myfolder/myfile.txt"; upload(hostName, username, password, localFilePath, remoteFilePath); } // Method to upload a file in Remote server public static void upload(String hostName, String username, String password, String localFilePath, String remoteFilePath) { File file = new File(localFilePath); if (!file.exists()) throw new RuntimeException("Error. Local file not found"); StandardFileSystemManager manager = new StandardFileSystemManager(); try { manager.init(); // Create local file object FileObject localFile = manager.resolveFile(file.getAbsolutePath()); // Create remote file object FileObject remoteFile = manager.resolveFile( createConnectionString(hostName, username, password, remoteFilePath), createDefaultOptions()); // Copy local file to sftp server remoteFile.copyFrom(localFile, Selectors.SELECT_SELF); System.out.println("File upload success"); } catch (Exception e) { throw new RuntimeException(e); } finally { manager.close(); } } // Establishing connection public static String createConnectionString(String hostName, String username, String password, String remoteFilePath) { return "sftp://" + username + ":" + password + "@" + hostName + "/" + remoteFilePath; } // Method to setup default SFTP config: public static FileSystemOptions createDefaultOptions() throws FileSystemException { // Create SFTP options FileSystemOptions opts = new FileSystemOptions(); // SSH Key checking SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking( opts, "no"); // Root directory set to user home SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true); // Timeout is count by Milliseconds SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000); return opts; } }
Note : Setting the UserDirIsRoot to true , make you to upload file/ Create new folder in current directory. SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
Setting it to false , enables you to upload file in any path from root directory.