java編寫Http伺服器下載工具_java

來源:互聯網
上載者:User

這個工具比較簡單,用於配合另外一個工具進行檔案傳送,廢話少說,上代碼

import java.net.URL;import java.net.URLConnection;import java.io.File;import java.io.InputStream;import java.io.FileOutputStream;import java.io.FileNotFoundException;import java.io.IOException;import org.apache.commons.io.FileUtils;public class HttpUtil{  private String httppath = "";  public void setHttpPath(String httppath){    this.httppath = httppath;  }  public String getHttpPath(){    return this.httppath;  }  public HttpUtil(String httppath){    this.httppath = httppath;  }  public InputStream getStream(String url){    InputStream inStream = null;    try{      URL httpurl = new URL(url);      URLConnection conn = httpurl.openConnection();      inStream = conn.getInputStream();    }catch (Exception e){      e.printStackTrace();      return null;    }    return inStream;  }  public int downLoad(String url,String localName ,int lines) throws FileNotFoundException, IOException{    FileOutputStream fos = null;    InputStream inStream = null;    int ret = 0;    try{      URL httpurl = new URL(url);      URLConnection conn = httpurl.openConnection();      inStream = conn.getInputStream();      fos = new FileOutputStream(localName);      byte[] b = new byte[102400];      int j = 0;      while(inStream.read(b) != -1 && lines > 0){        for(int i = j; i < b.length; i++){          if(b[i] == '\n'){            fos.write(b, j, i - j + 1);            lines--;            if(lines <= 0){              break;            }            j = i + 1;            continue;          }        }      }    }catch (Exception e){      e.printStackTrace();      ret = -1;    }finally {      fos.close();      inStream.close();      return ret;    }  }  public static void main(String[] args){    String httppath = "";    int lines = 0;    String localName = "";    try{      httppath = args[0];      localName = args[1];      lines = Integer.parseInt(args[2]);    }catch (Exception e){      e.printStackTrace();      return;    }    try{      HttpUtil hu = new HttpUtil(httppath);      hu.downLoad(hu.getHttpPath(),localName ,lines);    }catch (Exception e){      e.printStackTrace();    }  }}

這個工具實現了從HTTP伺服器上下載指定行數的檔案,並且不會因為編碼的問題引起下載的檔案內容亂碼
三個工具已經搞定,下一次就是把這三個工具結合起來將HTTP、FTP的檔案轉移到HDFS上

hadoop工具
ftp工具

以上就是本文所述的全部內容了,希望大家能喜歡。

請您花一點時間將文章分享給您的朋友或者留下評論。我們將會由衷感謝您的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.