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.
SFTP Using Java (VFS jar)
Download and add the below library in your class path.
Using the below java code we can perform the following operation in a SFTP server
1. Upload a file intO Remote server using SFTP
2. Download a file from Remote server using SFTP
3. Delete a file in remote system using sftp
4. Rename a file in remote system using SFTP
** UPDATE: FTP Complete tutorial now available here.
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 SftpExample {
public static void main(String[] args) {
String hostName = "localhost";
String username = "admin";
String password = "admin";
String localFilePath = "C:/text.txt";
String remoteFilePath = "/test/text.txt";
upload(hostName, username, password, localFilePath, remoteFilePath);
exist(hostName, username, password, remoteFilePath);
download(hostName, username, password, localFilePath, remoteFilePath);
delete(hostName, username, password, 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();
}
}
// Download file function:
public static void download(String hostName, String username,
String password, String localFilePath, String remoteFilePath) {
StandardFileSystemManager manager = new StandardFileSystemManager();
try {
manager.init();
String downloadFilePath = localFilePath.substring(0,
localFilePath.lastIndexOf("."))
+ "_downlaod_from_sftp"
+ localFilePath.substring(localFilePath.lastIndexOf("."),
localFilePath.length());
// Create local file object
FileObject localFile = manager.resolveFile(downloadFilePath);
// Create remote file object
FileObject remoteFile = manager.resolveFile(
createConnectionString(hostName, username, password,
remoteFilePath), createDefaultOptions());
// Copy local file to sftp server
localFile.copyFrom(remoteFile, Selectors.SELECT_SELF);
System.out.println("File download success");
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
manager.close();
}
}
// Delete file in remote system:
public static void delete(String hostName, String username,
String password, String remoteFilePath) {
StandardFileSystemManager manager = new StandardFileSystemManager();
try {
manager.init();
// Create remote object
FileObject remoteFile = manager.resolveFile(
createConnectionString(hostName, username, password,
remoteFilePath), createDefaultOptions());
if (remoteFile.exists()) {
remoteFile.delete();
System.out.println("Delete remote file success");
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
manager.close();
}
}
// Check remote file is exist function:
public static boolean exist(String hostName, String username,
String password, String remoteFilePath) {
StandardFileSystemManager manager = new StandardFileSystemManager();
try {
manager.init();
// Create remote object
FileObject remoteFile = manager.resolveFile(
createConnectionString(hostName, username, password,
remoteFilePath), createDefaultOptions());
System.out.println("File exist: " + remoteFile.exists());
return remoteFile.exists();
} 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;
}
}
Read More
