FTP, SFTP, FTPS examples In Java .

http://blog.csdn.net/luoshenhappy99/article/details/7448385

The FTP (File Transfer Protocol), FTPS (FTP over SSL), SFTP (FTP over SSH) and SCP (Secure Copy over SSH) . 

http://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPSClient.html


The examples of FTP/FTPs, the jar supporting them is org.apache.commons.net.ftp.

  1. import java.io.File;  
  2. import java.io.FileInputStream;  
  3. import java.io.FileOutputStream;  
  4. import java.io.IOException;  
  5. import java.security.NoSuchAlgorithmException;  
  6. import java.util.Vector;  
  7.   
  8. import org.apache.commons.net.ftp.FTPClient;  
  9. import org.apache.commons.net.ftp.FTPFile;  
  10. import org.apache.commons.net.ftp.FTPReply;  
  11. import org.apache.commons.net.ftp.FTPSClient;  
  12. import org.apache.log4j.Logger;  
  13.   
  14. public class FtpClient{  
  15.   
  16.     private static final Logger logger = Logger.getLogger(FtpClient.class);  
  17.   
  18.     private FTPClient client;  
  19.   
  20.     public FtpClient(boolean ftps) {  
  21.         if (ftps) {  
  22.             try {  
  23.                 client = new FTPSClient(true);  
  24.             } catch (NoSuchAlgorithmException e) {  
  25.                 e.printStackTrace();  
  26.             }  
  27.         } else {  
  28.             client = new FTPClient();  
  29.         }  
  30.     }  
  31.   
  32.     public boolean changeDir(String remotePath) throws Exception {  
  33.         return client.changeWorkingDirectory(remotePath);  
  34.     }  
  35.   
  36.     public boolean connect(String host, String login, String password, int port) throws Exception {  
  37.         logger.debug("FTP request connect to " + host + ":" + port);  
  38.         client.connect(host, port);  
  39.         int reply = client.getReplyCode();  
  40.         if (FTPReply.isPositiveCompletion(reply)) {  
  41.             logger.debug("FTP request login as " + login);  
  42.             if (client.login(login, password)) {  
  43.                 client.enterLocalPassiveMode();  
  44.                 return true;  
  45.             }  
  46.         }  
  47.         disconnect();  
  48.         return false;  
  49.     }  
  50.   
  51.     public void disconnect() throws Exception {  
  52.         logger.debug("FTP request disconnect");  
  53.         client.disconnect();  
  54.     }  
  55.   
  56.   
  57.     protected boolean downloadFileAfterCheck(String remotePath, String localFile) throws IOException {  
  58.   
  59.         boolean rst;  
  60.         FileOutputStream out = null;  
  61.         try {  
  62.             File file = new File(localFile);  
  63.             if (!file.exists()) {  
  64.                 out = new FileOutputStream(localFile);  
  65.                 rst = client.retrieveFile(remotePath, out);  
  66.             } else {  
  67.                 rst = true;  
  68.             }  
  69.         } finally {  
  70.             if (out != null) {  
  71.                 out.close();  
  72.             }  
  73.         }  
  74.         if (out != null) {  
  75.             out.close();  
  76.         }  
  77.         return rst;  
  78.     }  
  79.   
  80.     protected boolean downloadFile(String remotePath, String localFile) throws IOException {  
  81.   
  82.         boolean rst;  
  83.         FileOutputStream out = null;  
  84.         try {  
  85.             out = new FileOutputStream(localFile);  
  86.             rst = client.retrieveFile(remotePath, out);  
  87.         } finally {  
  88.             if (out != null) {  
  89.                 out.close();  
  90.             }  
  91.         }  
  92.         return rst;  
  93.     }  
  94.   
  95.     public Vector<String> listFileInDir(String remoteDir) throws Exception {  
  96.         if (changeDir(remoteDir)) {  
  97.             FTPFile[] files = client.listFiles();  
  98.             Vector<String> v = new Vector<String>();  
  99.             for (FTPFile file : files) {  
  100.                 if (!file.isDirectory()) {  
  101.                     v.addElement(file.getName());  
  102.                 }  
  103.             }  
  104.             return v;  
  105.         } else {  
  106.             return null;  
  107.         }  
  108.     }  
  109.   
  110.     public boolean uploadFile(String localFile, String remotePath) throws IOException {  
  111.         FileInputStream in = new FileInputStream(localFile);  
  112.         boolean rst;  
  113.         try {  
  114.             rst = client.storeFile(remotePath, in);  
  115.         } finally {  
  116.             in.close();  
  117.         }  
  118.         return rst;  
  119.     }  
  120.   
  121.     @Override  
  122.     public Vector<String> listSubDirInDir(String remoteDir) throws Exception {  
  123.         if (changeDir(remoteDir)) {  
  124.             FTPFile[] files = client.listFiles();  
  125.             Vector<String> v = new Vector<String>();  
  126.             for (FTPFile file : files) {  
  127.                 if (file.isDirectory()) {  
  128.                     v.addElement(file.getName());  
  129.                 }  
  130.             }  
  131.             return v;  
  132.         } else {  
  133.             return null;  
  134.         }  
  135.     }  
  136.   
  137.     protected boolean createDirectory(String dirName) {  
  138.         try {  
  139.             return client.makeDirectory(dirName);  
  140.         } catch (IOException e) {  
  141.             e.printStackTrace();  
  142.         }  
  143.         return false;  
  144.     }  
  145.   
  146.   
  147.     public boolean isARemoteDirectory(String path) {  
  148.         String cache = "/";  
  149.         try {  
  150.             cache = client.printWorkingDirectory();  
  151.         } catch (NullPointerException e) {  
  152.             //nop   
  153.         } catch (IOException e) {  
  154.             e.printStackTrace();  
  155.         }  
  156.         try {  
  157.             boolean isDir = changeDir(path);  
  158.             changeDir(cache);  
  159.             return isDir;  
  160.         } catch (IOException e) {  
  161.             //e.printStackTrace();  
  162.         } catch (Exception e) {  
  163.             //e.printStackTrace();  
  164.         }  
  165.         return false;  
  166.     }  
  167.   
  168.     public String getWorkingDirectory() {  
  169.         try {  
  170.             return client.printWorkingDirectory();  
  171.         } catch (IOException e) {  
  172.         }  
  173.         return null;  
  174.     }  
  175.   
  176. }  
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.Vector;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.ftp.FTPSClient;
import org.apache.log4j.Logger;

public class FtpClient{

	private static final Logger logger = Logger.getLogger(FtpClient.class);

	private FTPClient client;

	public FtpClient(boolean ftps) {
		if (ftps) {
			try {
				client = new FTPSClient(true);
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			}
		} else {
			client = new FTPClient();
		}
	}

	public boolean changeDir(String remotePath) throws Exception {
		return client.changeWorkingDirectory(remotePath);
	}

	public boolean connect(String host, String login, String password, int port) throws Exception {
		logger.debug("FTP request connect to " + host + ":" + port);
		client.connect(host, port);
		int reply = client.getReplyCode();
		if (FTPReply.isPositiveCompletion(reply)) {
			logger.debug("FTP request login as " + login);
			if (client.login(login, password)) {
				client.enterLocalPassiveMode();
				return true;
			}
		}
		disconnect();
		return false;
	}

	public void disconnect() throws Exception {
		logger.debug("FTP request disconnect");
		client.disconnect();
	}


	protected boolean downloadFileAfterCheck(String remotePath, String localFile) throws IOException {

		boolean rst;
		FileOutputStream out = null;
		try {
			File file = new File(localFile);
			if (!file.exists()) {
				out = new FileOutputStream(localFile);
				rst = client.retrieveFile(remotePath, out);
			} else {
				rst = true;
			}
		} finally {
			if (out != null) {
				out.close();
			}
		}
		if (out != null) {
			out.close();
		}
		return rst;
	}

	protected boolean downloadFile(String remotePath, String localFile) throws IOException {

		boolean rst;
		FileOutputStream out = null;
		try {
			out = new FileOutputStream(localFile);
			rst = client.retrieveFile(remotePath, out);
		} finally {
			if (out != null) {
				out.close();
			}
		}
		return rst;
	}

	public Vector<String> listFileInDir(String remoteDir) throws Exception {
		if (changeDir(remoteDir)) {
			FTPFile[] files = client.listFiles();
			Vector<String> v = new Vector<String>();
			for (FTPFile file : files) {
				if (!file.isDirectory()) {
					v.addElement(file.getName());
				}
			}
			return v;
		} else {
			return null;
		}
	}

	public boolean uploadFile(String localFile, String remotePath) throws IOException {
		FileInputStream in = new FileInputStream(localFile);
		boolean rst;
		try {
			rst = client.storeFile(remotePath, in);
		} finally {
			in.close();
		}
		return rst;
	}

	@Override
	public Vector<String> listSubDirInDir(String remoteDir) throws Exception {
		if (changeDir(remoteDir)) {
			FTPFile[] files = client.listFiles();
			Vector<String> v = new Vector<String>();
			for (FTPFile file : files) {
				if (file.isDirectory()) {
					v.addElement(file.getName());
				}
			}
			return v;
		} else {
			return null;
		}
	}

	protected boolean createDirectory(String dirName) {
		try {
			return client.makeDirectory(dirName);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}


	public boolean isARemoteDirectory(String path) {
		String cache = "/";
		try {
			cache = client.printWorkingDirectory();
		} catch (NullPointerException e) {
			//nop
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			boolean isDir = changeDir(path);
			changeDir(cache);
			return isDir;
		} catch (IOException e) {
			//e.printStackTrace();
		} catch (Exception e) {
			//e.printStackTrace();
		}
		return false;
	}

	public String getWorkingDirectory() {
		try {
			return client.printWorkingDirectory();
		} catch (IOException e) {
		}
		return null;
	}

}



 


the example of SFTP, the jar supporting this is com.jcraft.jsch


  1. import java.io.File;  
  2. import java.io.FileInputStream;  
  3. import java.io.FileOutputStream;  
  4. import java.io.IOException;  
  5. import java.util.Vector;  
  6.   
  7. import org.apache.commons.vfs.FileSystemException;  
  8. import org.apache.commons.vfs.FileSystemOptions;  
  9. import org.apache.commons.vfs.provider.sftp.SftpClientFactory;  
  10. import org.apache.commons.vfs.provider.sftp.SftpFileSystemConfigBuilder;  
  11.   
  12. import com.jcraft.jsch.Channel;  
  13. import com.jcraft.jsch.ChannelSftp;  
  14. import com.jcraft.jsch.JSchException;  
  15. import com.jcraft.jsch.Session;  
  16. import com.jcraft.jsch.SftpException;  
  17. import com.jcraft.jsch.ChannelSftp.LsEntry;  
  18.   
  19. public class SFTPClient{  
  20.   
  21.     private ChannelSftp command;  
  22.   
  23.     private Session session;  
  24.   
  25.     public SFTPClient() {  
  26.         command = null;  
  27.     }  
  28.   
  29.     public boolean connect(String host, String login, String password, int port) throws JSchException {  
  30.   
  31.         //If the client is already connected, disconnect  
  32.         if (command != null) {  
  33.             disconnect();  
  34.         }  
  35.         FileSystemOptions fso = new FileSystemOptions();  
  36.         try {  
  37.             SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(fso, "no");  
  38.             session = SftpClientFactory.createConnection(host, port, login.toCharArray(), password.toCharArray(), fso);  
  39.             Channel channel = session.openChannel("sftp");  
  40.             channel.connect();  
  41.             command = (ChannelSftp) channel;  
  42.   
  43.         } catch (FileSystemException e) {  
  44.             e.printStackTrace();  
  45.             return false;  
  46.         }  
  47.         return command.isConnected();  
  48.     }  
  49.   
  50.     public void disconnect() {  
  51.         if (command != null) {  
  52.             command.exit();  
  53.         }  
  54.         if (session != null) {  
  55.             session.disconnect();  
  56.         }  
  57.         command = null;  
  58.     }  
  59.   
  60.     public Vector<String> listFileInDir(String remoteDir) throws Exception {  
  61.         try {  
  62.             Vector<LsEntry> rs = command.ls(remoteDir);  
  63.             Vector<String> result = new Vector<String>();  
  64.             for (int i = 0; i < rs.size(); i++) {  
  65.                 if (!isARemoteDirectory(rs.get(i).getFilename())) {  
  66.                     result.add(rs.get(i).getFilename());  
  67.                 }  
  68.             }  
  69.             return result;  
  70.         } catch (Exception e) {  
  71.             e.printStackTrace();  
  72.             System.err.println(remoteDir);  
  73.             throw new Exception(e);  
  74.         }  
  75.     }  
  76.   
  77.     public Vector<String> listSubDirInDir(String remoteDir) throws Exception {  
  78.         Vector<LsEntry> rs = command.ls(remoteDir);  
  79.         Vector<String> result = new Vector<String>();  
  80.         for (int i = 0; i < rs.size(); i++) {  
  81.             if (isARemoteDirectory(rs.get(i).getFilename())) {  
  82.                 result.add(rs.get(i).getFilename());  
  83.             }  
  84.         }  
  85.         return result;  
  86.     }  
  87.   
  88.     protected boolean createDirectory(String dirName) {  
  89.         try {  
  90.             command.mkdir(dirName);  
  91.         } catch (Exception e) {  
  92.             return false;  
  93.         }  
  94.         return true;  
  95.     }  
  96.   
  97.     protected boolean downloadFileAfterCheck(String remotePath, String localPath) throws IOException {  
  98.         FileOutputStream outputSrr = null;  
  99.         try {  
  100.             File file = new File(localPath);  
  101.             if (!file.exists()) {  
  102.                 outputSrr = new FileOutputStream(localPath);  
  103.                 command.get(remotePath, outputSrr);  
  104.             }  
  105.         } catch (SftpException e) {  
  106.             try {  
  107.                 System.err.println(remotePath + " not found in " + command.pwd());  
  108.             } catch (SftpException e1) {  
  109.                 e1.printStackTrace();  
  110.             }  
  111.             e.printStackTrace();  
  112.             return false;  
  113.         } finally {  
  114.             if (outputSrr != null) {  
  115.                 outputSrr.close();  
  116.             }  
  117.         }  
  118.         return true;  
  119.     }  
  120.   
  121.     protected boolean downloadFile(String remotePath, String localPath) throws IOException {  
  122.         FileOutputStream outputSrr = new FileOutputStream(localPath);  
  123.         try {  
  124.             command.get(remotePath, outputSrr);  
  125.         } catch (SftpException e) {  
  126.             try {  
  127.                 System.err.println(remotePath + " not found in " + command.pwd());  
  128.             } catch (SftpException e1) {  
  129.                 e1.printStackTrace();  
  130.             }  
  131.             e.printStackTrace();  
  132.             return false;  
  133.         } finally {  
  134.             if (outputSrr != null) {  
  135.                 outputSrr.close();  
  136.             }  
  137.         }  
  138.         return true;  
  139.     }  
  140.   
  141.     protected boolean uploadFile(String localPath, String remotePath) throws IOException {  
  142.         FileInputStream inputSrr = new FileInputStream(localPath);  
  143.         try {  
  144.             command.put(inputSrr, remotePath);  
  145.         } catch (SftpException e) {  
  146.             e.printStackTrace();  
  147.             return false;  
  148.         } finally {  
  149.             if (inputSrr != null) {  
  150.                 inputSrr.close();  
  151.             }  
  152.         }  
  153.         return true;  
  154.     }  
  155.   
  156.     public boolean changeDir(String remotePath) throws Exception {  
  157.         try {  
  158.             command.cd(remotePath);  
  159.         } catch (SftpException e) {  
  160.             return false;  
  161.         }  
  162.         return true;  
  163.     }  
  164.   
  165.     public boolean isARemoteDirectory(String path) {  
  166.         try {  
  167.             return command.stat(path).isDir();  
  168.         } catch (SftpException e) {  
  169.             //e.printStackTrace();  
  170.         }  
  171.         return false;  
  172.     }  
  173.   
  174.     public String getWorkingDirectory() {  
  175.         try {  
  176.             return command.pwd();  
  177.         } catch (SftpException e) {  
  178.             e.printStackTrace();  
  179.         }  
  180.         return null;  
  181.     }  
  182.   
  183. }  

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值