Monday, 17 August 2015

java - How do you upload a file to an FTP server?

import java.io.File;
import java.io.FileNotFoundException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.vfs2.FileObject;
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 void onUpload()
{
String hostName = "xxxxxxx";
String username = "xxxxxxx";
String password = "xxxxxxx";
String ftpfolder = "outbound";

String fileName ="YourLocalFileName";
String remoteFilePath = "/" + ftpfolder + "/" + fileName;
String localFilePath = "YourLocalFilePath";
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 SFTP options
FileSystemOptions opts = new FileSystemOptions();

// SSH Key checking
SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(
opts, "no");
// Root directory set to user home
SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts,
false);

// Timeout is count by Milliseconds
SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);

// Create remote file object
FileObject remoteFile = manager.resolveFile(
createConnectionString(hostName, username, password,
remoteFilePath), opts);

// Copy local file to sftp server
remoteFile.copyFrom(localFile, Selectors.SELECT_SELF);
System.out.println("Done");
} catch (Exception e) {
//Catch and Show the exception
} finally {
manager.close();
win.detach();
}
}


public static String createConnectionString(String hostName,
String username, String password, String remoteFilePath) {
return "sftp://" + username + ":" + password + "@" + hostName + "/"
+ remoteFilePath;
}

Maven artifacts for Apache VFS is a Virtual File System library.


<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-vfs2</artifactId>
<version>2.0</version>
</dependency>

No comments:

Post a Comment