java ftp和sftp上传下载

文章目录

ftp

package com.ws;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FTPUtil {
	
	static Logger l=LoggerFactory.getLogger(FTPUtil.class);
	
	//ftp地址
	public static String hostname="";
	public static int port=22;
	public static String username="";
	public static String password="";
	public static String workingPath="";
	
	public static void main(String[] args) {
		FTPClient ftpClient = new FTPClient();
		connect(ftpClient);
		disconnect(ftpClient);
	}
	
	/**
	 * 上传
     *
     * @param hostname ip或域名地址
     * @param port  端口
     * @param username 用户名
     * @param password 密码
     * @param workingPath 服务器的工作目
     * @param inputStream 要上传文件的输入流
     * @param saveName    设置上传之后的文件名
     * @return
     */
    public static boolean upload(InputStream inputStream, String saveName) {
        boolean flag = false;
        FTPClient ftpClient = new FTPClient();
        //1 测试连接
        if (connect(ftpClient)) {
            try {
                //2 检查工作目录是否存在
                if (ftpClient.changeWorkingDirectory(workingPath)) {
                    // 3 检查是否上传成功
                	flag=ftpClient.storeFile(saveName, inputStream);
                	//l.info(saveName+"上传成功");
                }else {
                	l.info("工作目录不存在");
                }
            } catch (IOException e) {
                e.printStackTrace();
                disconnect(ftpClient);
            }
        }
        disconnect(ftpClient);
        return flag;
    }
 
    /**
      * 测试是否能连接
     *
     * @param ftpClient
     * @param hostname  ip或域名地址
     * @param port      端口
     * @param username  用户名
     * @param password  密码
     * @return 返回真则能连接
     */
    public static boolean connect(FTPClient ftpClient) {
        boolean flag = false;
        try {
            //ftp初始化的一些参数
            ftpClient.connect(hostname, port);
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            //ftpClient.setControlEncoding("GBK");
            if (ftpClient.login(username, password)) {
                //l.info("连接ftp成功");
                flag = true;
            } else {
                //l.info("连接ftp失败,可能用户名或密码错误");
                disconnect(ftpClient);
            }
        } catch (IOException e) {
            //l.info("连接失败,可能ip或端口错误");
            disconnect(ftpClient);
            e.printStackTrace();
        }
        return flag;
    }
 
    /**
      * 断开连接
     *
     * @param ftpClient
     * @throws Exception
     */
    public static void disconnect(FTPClient ftpClient) {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
                //l.info("已关闭连接");
            } catch (IOException e) {
                //l.info("没有关闭连接");
                e.printStackTrace();
            }
        }
    }
    
    /**
     	* 从ftp服务器下载
     */
    public static boolean downLoadFile(OutputStream out, String flieName) {
		boolean flag = true;
		FTPClient ftpClient = new FTPClient();
		//1 测试连接
		if (connect(ftpClient)) {
		    try {
		        //2 检查工作目录是否存在
		        //if (ftpClient.changeWorkingDirectory(workingPath)) {
		        // 3 检查是否上传成功
		    	//System.out.println(flieName);
		    	flieName=new String(flieName.getBytes("GBK"),FTP.DEFAULT_CONTROL_ENCODING);
	        	ftpClient.retrieveFile(flieName,new BufferedOutputStream(out));
		        //}
	        } catch (IOException e) {
	            e.printStackTrace();
	            disconnect(ftpClient);
	        }
		 }
	   disconnect(ftpClient);
       return flag;
   }
    
}

sftp

package com.ws;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class SFTPUtil {
	
	static Logger l=LoggerFactory.getLogger(SFTPUtil.class);
	
	//sftp地址
	public static String hostname="";
	public static int port=22;
	public static String username="";
	public static String password="";
	public static String cdPath="";
	public static String workingPath="";

	public static void main(String[] args) throws Exception {
		InputStream in=new ByteArrayInputStream("1".getBytes());
        upload(in, workingPath+"1.txt");
		OutputStream out=new ByteArrayOutputStream();

		downLoadFile(out, workingPath+"1.txt");
		System.out.println(out.toString());
         System.out.println(1);
	}
	
	/**
	 * 上传
     *
     * @param hostname ip或域名地址
     * @param port  端口
     * @param username 用户名
     * @param password 密码
     * @param workingPath 服务器的工作目
     * @param inputStream 要上传文件的输入流
     * @param saveName    设置上传之后的文件名
     * @return
     */
    public static boolean upload(InputStream inputStream, String saveName) {
    	ChannelSftp sftp=null;
    	Session sshSession=connect();
		try {
			sftp = (ChannelSftp)sshSession.openChannel("sftp");
			sftp.connect(10000);
			sftp.cd(cdPath);
	    	sftp.put(inputStream, saveName);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        disconnect(sshSession,sftp);
        return true;
    }
 
    /**
     	* 从ftp服务器下载
     */
    public static boolean downLoadFile(OutputStream out, String flieName) {
    	ChannelSftp sftp=null;
    	Session sshSession=connect();
		try {
			sftp = (ChannelSftp)sshSession.openChannel("sftp");
			sftp.connect(10000);
			sftp.cd(cdPath);
	    	sftp.get(flieName, out);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        disconnect(sshSession,sftp);
        return true;
   }

    public static Session connect() {
    	Session sshSession=null;
    	try {	
			 JSch jsch = new JSch();
			 sshSession = jsch.getSession(username, hostname, port);
			 sshSession.setPassword(password);
			 Properties sshConfig = new Properties();
	         sshConfig.put("StrictHostKeyChecking", "no");
	         sshSession.setConfig(sshConfig);
			 sshSession.connect();
		}catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return sshSession;
    }
    
    /**
     * 断开连接
 */
   public static void disconnect(Session sshSession,ChannelSftp sftp) {
   	 if (sftp != null){
       if (sftp.isConnected()) {
          sftp.disconnect();
        }
     }
 	 if (sshSession != null){
       if (sshSession.isConnected()){
         sshSession.disconnect();
       }
     }
}
}


上一篇:sftp常用命令


下一篇:linux(1)Mac上传文件到Linux服务器