上傳文件到服務器指定位置 & 從服務器指定位置下載文件

須要的jar包:

  去maven倉庫本身搜索com.jcraft下載jar包java

<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(); } } } } }
點擊查看
相關文章
相關標籤/搜索