上传文件到服务器指定位置 & 从服务器指定位置下载文件

需要的jar包:

  去maven仓库自己搜索com.jcraft下载jar包

<dependency>  
  <groupId>com.jcraft</groupId>  
  <artifactId>jsch</artifactId>  
  <version>0.1.49</version>  
</dependency>  

 上传:

  ftp方式:

package com.sunsheen.jfids.studio.monitor.sender;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.sunsheen.jfids.studio.monitor.common.LogInfo;
/**
 * 上传到远程服务器
 * @author WangSong
 *
 */
public class SendLogByFtp {
    
    /**
     * 文件上传
     * @param username    服务器用户名
     * @param password    服务器密码
     * @param address    服务器ip
     * @param port        连接服务器的端口号(默认22)
     * @param file        上传的文件
     */
    public static void postFile(String username,String password,String address,int port,File file){
        ChannelSftp sftp = null;
        Channel channel = null;
        Session sshSession = null;
        try {
            //创建连接
            JSch jsch = new JSch();
            sshSession = jsch.getSession(username, address, port);
            sshSession.setPassword(password);
            //获取session
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            //得到sftp
            channel = sshSession.openChannel("sftp");
            channel.connect();
            sftp = (ChannelSftp) channel;
            //进入存放日志文件的目录
            sftp.cd(LogInfo.SERVERS_RECIVE_FOLDER);
            //上传
            sftp.put(new FileInputStream(file), LogInfo.LOGS_ZIP_FILE_NAME);
            System.out.println("上传成功!");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭sftp信道
            if (sftp != null) {
                if (sftp.isConnected()) {
                    sftp.disconnect();
                }
            }
            //关闭channel管道
            if (channel != null) {
                if (channel.isConnected()) {
                    channel.disconnect();
                }
            }
            //关闭session
            if (sshSession != null) {
                if (sshSession.isConnected()) {
                    sshSession.disconnect();
                }
            }
        }        
    }
    
}
点击查看源码

  http方式:

package com.sunsheen.jfids.studio.monitor.sender;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.FormBodyPart;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.eclipse.core.runtime.Assert;

/**
 * 發送日誌文件到服務器 :需要将文件打包压缩
 * 
 * @author WangSong
 *
 */
public class SendLogByHttp {

    /**
     * 发送日志文件
     * @param url        远程地址
     * @param param        String类型的map数据,可以为空
     * @param file        上传的文件
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String postFile(String url, Map<String, Object> param,
            File file) throws ClientProtocolException, IOException {
        
        String res = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();//创建http客户端
        HttpPost httppost = new HttpPost(url);
        httppost.setEntity(getMutipartEntry(param, file));//设置发送的消息体
        
        CloseableHttpResponse response = httpClient.execute(httppost);//发送消息到指定服务器 
        
        HttpEntity entity = response.getEntity();
        
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            res = EntityUtils.toString(entity, "UTF-8");
            response.close();
        } else {
            res = EntityUtils.toString(entity, "UTF-8");
            response.close();
            throw new IllegalArgumentException(res);
        }
        return res;
    }

    //得到当前文件实体
    private static MultipartEntity getMutipartEntry(Map<String, Object> param,
            File file) throws UnsupportedEncodingException {
        Assert.isTrue(null == file, "文件不能为空!");
        
        FileBody fileBody = new FileBody(file);//通过文件路径,得到文件体
        FormBodyPart filePart = new FormBodyPart("file", fileBody);//格式化
        MultipartEntity multipartEntity = new MultipartEntity();
        multipartEntity.addPart(filePart);

        if(null != param){
            Iterator<String> iterator = param.keySet().iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                FormBodyPart field = new FormBodyPart(key, new StringBody(
                        (String) param.get(key)));
                multipartEntity.addPart(field);
            }
        }

        return multipartEntity;
    }

}
点击查看

  socket方式:

package com.sunsheen.jfids.studio.monitor.sender;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;

/**
 * 通過socket通信,發送文件
 * @author WangSong
 *
 */
public class SendLogBySocket {

    /**
     * 文件上傳
     * @param address    远程服务器地址
     * @param port        远程服务器开放的端口号
     * @param file        上传的文件
     */
    public static void postFile(String address,int port,File file) {
        Socket st = null;
        BufferedOutputStream bos = null;
        FileInputStream fis = null;
        try {
            //指定端口号
            //InetAddress.getLocalHost();
            st = new Socket(address,port);
            //要上传文件位置
            bos = new BufferedOutputStream(st.getOutputStream());
            fis = new FileInputStream(file);
            int len = 0;
            byte b[] = new byte[1024];
            //文件写入
            while ((len = fis.read(b)) != -1) {
                bos.write(b, 0, len);
                bos.flush();
            }
            System.out.println("客户端上传完成!");
        }
        catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                //关闭资源
                fis.close();
                bos.close();
                st.close();
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
}
点击查看

下载

package com.sunsheen.jfids.studio.monitor.download;

import java.util.Properties;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.sunsheen.jfids.studio.monitor.HKMoniter;
import com.sunsheen.jfids.studio.monitor.HKMoniterFactory;
import com.sunsheen.jfids.studio.monitor.common.LogInfo;

/**
 * 下载服务器上的日志文件到本地
 * 
 * @author WangSong
 *
 */
public class DownloadLog {
    private final static HKMoniter logger = HKMoniterFactory.getLogger(DownloadLog.class.getName());

    public static void downloadLogs(String username, String password, String address,
            int port) {
        ChannelSftp sftp = null;
        Channel channel = null;
        Session sshSession = null;
        try {
            // 创建连接
            JSch jsch = new JSch();
            sshSession = jsch.getSession(username, address, port);
            sshSession.setPassword(password);
            // 获取session
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            // 得到sftp
            channel = sshSession.openChannel("sftp");
            channel.connect();
            sftp = (ChannelSftp) channel;
            // 进入存放日志文件的目录
            sftp.cd(LogInfo.SERVERS_RECIVE_FOLDER);
            // 下载
            sftp.get(LogInfo.SERVERS_RECIVE_FOLDER + "/"+LogInfo.LOGS_ZIP_FILE_NAME,LogInfo.LOCAL_LOG_PATH);
            System.out.println("下载成功!");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭sftp信道
            if (sftp != null) {
                if (sftp.isConnected()) {
                    sftp.disconnect();
                }
            }
            // 关闭channel管道
            if (channel != null) {
                if (channel.isConnected()) {
                    channel.disconnect();
                }
            }
            // 关闭session
            if (sshSession != null) {
                if (sshSession.isConnected()) {
                    sshSession.disconnect();
                }
            }
        }
    }

}
点击查看
原文地址:https://www.cnblogs.com/Soy-technology/p/11662239.html