Pages Navigation Menu

Coding is much easier than you think

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;
	}

}

2 Comments

  1. Try this,

    “sftp://” + userId + “:” + password + “@”+ srcIPAddress + “:22” + “/” + srcFileName;

  2. I am trying in ubuntu. I am getting run:
    Aug 09, 2014 9:40:35 PM org.apache.commons.vfs2.impl.StandardFileSystemManager info
    INFO: Using “/tmp/vfs_cache” as temporary files store.
    Exception in thread “main” java.lang.RuntimeException: org.apache.commons.vfs2.FileSystemException: Invalid URI escape sequence “%@1”.
    at sftp.SFTP.upload(SFTP.java:62)
    at sftp.SFTP.main(SFTP.java:31)
    Caused by: org.apache.commons.vfs2.FileSystemException: Invalid URI escape sequence “%@1”.
    at org.apache.commons.vfs2.provider.UriParser.decode(UriParser.java:343)
    at org.apache.commons.vfs2.provider.UriParser.decode(UriParser.java:308)
    at org.apache.commons.vfs2.provider.UriParser.checkUriEncoding(UriParser.java:462)
    at org.apache.commons.vfs2.impl.DefaultFileSystemManager.resolveFile(DefaultFileSystemManager.java:678)
    at org.apache.commons.vfs2.impl.DefaultFileSystemManager.resolveFile(DefaultFileSystemManager.java:621)
    at sftp.SFTP.upload(SFTP.java:53)
    … 1 more
    Java Result: 1

    Please resolve my error . Following line results error i guess. how to resolve this.
    String localFilePath = “/home/decathlon/car.csv”;