当前位置: 移动技术网 > IT编程>开发语言>Java > java编写Http服务器下载工具

java编写Http服务器下载工具

2019年07月22日  | 移动技术网IT编程  | 我要评论

长泰古山重,天水怡景,芦荟怎么美容

这个工具比较简单,用于配合另外一个工具进行文件传送,废话少说,上代码

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上

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

请您花一点时间将文章分享给您的朋友或者留下评论。我们将会由衷感谢您的支持!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网