您好,欢迎访问代理记账网站
  • 价格透明
  • 信息保密
  • 进度掌控
  • 售后无忧

java ftp和sftp上传下载

文章目录

    • 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();
       }
     }
}
}



分享:

低价透明

统一报价,无隐形消费

金牌服务

一对一专属顾问7*24小时金牌服务

信息保密

个人信息安全有保障

售后无忧

服务出问题客服经理全程跟进