sftp file Upload and download

Source: Internet
Author: User
Tags file transfer protocol

SFTP is the abbreviation for Secure File Transfer protocol, security File Transfer Protocol. You can provide a secure encryption method for transferring files. SFTP has almost the same syntax and functionality as FTP. SFTP is a part of SSH and is a secure way to transfer files to the Blogger server. In fact, in the SSH package, a secure file transfer subsystem called SFTP (secure files Transfer Protocol) has been included, and SFTP itself does not have a separate daemon. It must use the sshd daemon (the port number by default is 22) to complete the corresponding connection operation, so in a sense, sftp is not like a server program, but more like a client program. SFTP is also used to transmit authentication information and transmitted data using encryption, so it is very safe to use SFTP. However, because this transmission uses the encryption/decryption technology, the transfer efficiency is much lower than the normal FTP, and if you have higher network security requirements, you can use SFTP instead of FTP.

Here is the Java code sftp file upload and download specific implementation

1. Connecting Server classes

Package Test;

Import java.io.IOException;
Import Java.io.InputStream;
Import java.util.Properties;

Import Com.jcraft.jsch.Channel;
Import com.jcraft.jsch.ChannelSftp;
Import Com.jcraft.jsch.JSch;
Import com.jcraft.jsch.Session;

/*
* @author Lixiongjun
*
* Tool class for creating CHANNELSFTP communication objects using the Jsch package
* 2015-1-27 10:03:21
*/

public class Sftputil {

private static String IP = null; IP Host IP
private static int port =-1; Port host SSH2, if the default value, pass-1
private static String user = null; User Host login Username
private static String PSW = null; PSW Host Login Password
private static String ServicePath = null; Service Store file path
private static Properties prop = null;

private static Session session = NULL;
private static channel channel = NULL;

Reading the parameters of a configuration file
static {
Prop = new Properties ();
ClassLoader cl = SftpUtil.class.getClassLoader ();
InputStream is = cl
. getResourceAsStream ("test/sftp_updownload.properties");
try {
Prop.load (IS);
} catch (IOException e) {
SYSTEM.OUT.PRINTLN ("Error reading config file! ");
E.printstacktrace ();
}
ip = prop.getproperty ("IP");
Port = Integer.parseint (Prop.getproperty ("port"));
user = Prop.getproperty ("user");
PSW = Prop.getproperty ("PSW");
ServicePath = Prop.getproperty ("ServicePath");

}

/**
* Get SFTP Communication
*
* @return access to the CHANNELSFTP
* @throws Exception
*/

public static Channelsftp Getsftp () throws Exception {

Channelsftp sftp = null;
Jsch Jsch = new Jsch ();
if (port <= 0) {
Connect to server with default port
Session = jsch.getsession (user, IP);
} else {
Connect the server with the specified port
Session = jsch.getsession (user, IP, port);
}
Throws an exception if the server is not connected
if (session = = null) {
throw new Exception ("session is null");
}
Set the password for the login host
Session.setpassword (PSW);//Set Password
Set the first login prompt, optional value: (Ask | yes | no)
Session.setconfig ("stricthostkeychecking", "no");
Setting the login time-out period
Session.connect (30000);
try {
Create an SFTP communication channel
Channel = (channel) session.openchannel ("sftp");
Channel.connect ();
SFTP = (channelsftp) channel;
Enter the folder specified by the server
SFTP.CD (ServicePath);

} catch (Exception e) {
E.printstacktrace ();
}
return SFTP;
}

/**
* Close Connection
*/
public static void Closesftp () {
if (channel! = NULL) {
if (channel.isconnected ())
Channel.disconnect ();
}
if (session! = NULL) {
if (session.isconnected ())
Session.disconnect ();
}
}
}

2. Upload the Download tool class

Package Test;

Import Java.io.BufferedReader;
Import Java.io.BufferedWriter;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import Java.io.OutputStream;

Import Org.junit.Test;

Import com.jcraft.jsch.ChannelSftp;

public class Sftpuploadordownload {

/*
* @author Lixiongjun
*
* Tool class for uploading and downloading sftp files
* 2015-1-27 15:13:26
*/

/**
* Upload local file to server
* @param srcpath Local file path
* @param dstfilename Target file name
* @return Upload is successful
*/
public boolean upload (String srcpath,string dstfilename) {
Channelsftp Sftp=null;
try {
SFTP =sftputil.getsftp ();
Sftp.put (Srcpath,dstfilename);
return true;
} catch (Exception e) {
E.printstacktrace ();
return false;
}
finally{
Sftputil.closesftp ();
}
}


/**
* Upload local file to server
* @param in input stream
* @param dstfilename Target file name
* @return Upload is successful
*/
public boolean Uploadbystrem (InputStream in,string dstfilename) {
Channelsftp Sftp=null;
try {
SFTP =sftputil.getsftp ();
Sftp.put (In,dstfilename);
return true;
} catch (Exception e) {
E.printstacktrace ();
return false;
}
finally{
Sftputil.closesftp ();
}
}


/**
* Download server files to local
* @param despath Download to local destination path
* @param srcfilename Source file name
* @return Whether the download was successful
*/
public boolean download (String srcfilename,string dstpath) {
Channelsftp Sftp=null;
try {
SFTP =sftputil.getsftp ();
Sftp.get (Srcfilename,dstpath);
return true;
} catch (Exception e) {
E.printstacktrace ();
return false;
}
finally{
Sftputil.closesftp ();
}
}

/**
* Get the contents of server files, only valid for text files
* @param srcfilename Server source file name
* @return File contents
*/
public string Getservicefilecontext (string srcfilename) {
Channelsftp Sftp=null;
InputStream In=null;
BufferedReader Br=null;
String filecontext= "";
try {
SFTP =sftputil.getsftp ();
In=sftp.get (Srcfilename);
Br=new BufferedReader (New InputStreamReader (in));
String Str=br.readline ();
while (Str!=null) {
Filecontext+=str+ "\ n";
Str=br.readline ();
}

} catch (Exception e) {
E.printstacktrace ();
}
finally{
try {
Br.close ();
In.close ();
} catch (IOException e) {
E.printstacktrace ();
}
Sftputil.closesftp ();
}
return filecontext;
}

/**
* Delete files on server
* @param filename to delete
* @return Whether to delete the success
*/
public boolean remove (String filename) {
Channelsftp Sftp=null;
try {
SFTP =sftputil.getsftp ();
SFTP.RM (filename);
return true;
} catch (Exception e) {
E.printstacktrace ();
return false;
}
finally{
Sftputil.closesftp ();
}
}

@Test
public void Testsftpupload () {
if (Upload ("E:/test.txt", "test.txt")) {
System.out.println ("Upload file Success");
}
else{
System.out.println ("Upload file failed");
}
}

@Test
public void Testsftpdownload () {
if (Download ("Test.txt", "E:/downtest.txt")) {
System.out.println ("Download file succeeded");
}
else{
System.out.println ("Download file failed");
}
}

@Test
public void Testsftpgetservicefilecontext () {

String context=getservicefilecontext ("test.txt");
SYSTEM.OUT.PRINTLN (context);

}

@Test
public void Testsftpremove () {
if (Remove ("test.txt")) {
System.out.println ("Delete file succeeded");
}
else{
System.out.println ("Delete file failed");
}
}

}

Configuration file Sftp_updownload.properties

ip=127.0.0.1
Port=22
User=test
Psw=test
Servicepath=testpath

Download the Get method details API http://blog.csdn.net/rangqiwei/article/details/9002046

Upload the Put method details API http://www.cnblogs.com/longyg/archive/2012/06/25/2556576.html

sftp file Upload and download

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.