Skip to Main Content

Java Security

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

SFTP in Java

843811Jun 22 2010 — edited Jun 22 2010
Hi

I am making a connection to the Server but want to transfer a file to it. But currently my code work the other way around. It's taking the file from the server and putting the file in the local directory.

Also i would like to add a response back from the server when the file is completed.

Below is my code

package fileuploads;

import java.io.File;

import sun.security.action.GetLongAction;

import com.jscape.inet.ftp.*;
import com.jscape.inet.sftp.Sftp;
import com.jscape.inet.sftp.SftpException;
import com.jscape.inet.sftp.events.SftpAdapter;
import com.jscape.inet.sftp.events.SftpConnectedEvent;
import com.jscape.inet.sftp.events.SftpDisconnectedEvent;
import com.jscape.inet.ssh.util.SshParameters;

public class ConnectToUpload extends SftpAdapter{

private String ftpHostname = "xx.xx.xx.xx";
private String ftpUsername = "xxxx";
private String ftpPassword = "xxxxx";

public ConnectToUpload() {

this.ftpHostname = ftpHostname;
this.ftpUsername = ftpUsername;
this.ftpPassword = ftpPassword;
}

public void doUpload() throws SftpException {
SshParameters params = new SshParameters(ftpHostname, ftpUsername,
ftpPassword);
Sftp ftp = new Sftp(params);
ftp.addSftpListener(new ConnectToUpload());
ftp.connect();
String listing = ftp.getDirListingAsString();
System.out.println(listing);
ftp.setLocalDir(new File("C:/tmp"));
System.out.println(ftp.getLocalDir());
ftp.setDir("//dropzone/dropzone1/dropzone1/dev");
ftp.setAscii();
ftp.setBinary();
ftp.download("TestUpload.txt");
long offset = ftp.getFilesize("TestUpload.txt");
System.out.println(offset);
ftp.upload(new File("C:/tmp/TestUpload.txt"));
ftp.

ftp.disconnect();
System.out.println("Connection is FTP Site : " + ftpHostname
+ " has now disconnected");
}

/**
* Captures FtpConnectedEvent event
*/
public void connected(SftpConnectedEvent evt) {
System.out.println("Connected to server: " + evt.getHostname());
}

/**
* Captures FtpDisconnectedEvent event
*/
public void disconnected(SftpDisconnectedEvent evt) {
System.out.println("Disconnected from server: " + evt.getHostname());
}

public static void main(String[] args) {
String ftpHostname;
String ftpUsername;
String ftpPassword;
try {
ftpHostname = "xx.xxx.xx.xx";
ftpUsername = "xxxxxx";
ftpPassword = "xxxxx";

// ConnectToUpload example = new ConnectToUpload(ftpHostname,
// ftpUsername, ftpPassword);
//System.out.println("Using upload filter .*\\.txt");
ConnectToUpload example = new ConnectToUpload();
// print directory listing
example.doUpload();

} catch (Exception e) {
e.printStackTrace();
}
}
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jul 20 2010
Added on Jun 22 2010
2 comments
637 views