java编写Http服务器下载工具
这个工具比较简单,用于配合另外一个工具进行文件传送,废话少说,上代码
importjava.net.URL;
importjava.net.URLConnection;
importjava.io.File;
importjava.io.InputStream;
importjava.io.FileOutputStream;
importjava.io.FileNotFoundException;
importjava.io.IOException;
importorg.apache.commons.io.FileUtils;
publicclassHttpUtil{
privateStringhttppath="";
publicvoidsetHttpPath(Stringhttppath){
this.httppath=httppath;
}
publicStringgetHttpPath(){
returnthis.httppath;
}
publicHttpUtil(Stringhttppath){
this.httppath=httppath;
}
publicInputStreamgetStream(Stringurl){
InputStreaminStream=null;
try{
URLhttpurl=newURL(url);
URLConnectionconn=httpurl.openConnection();
inStream=conn.getInputStream();
}catch(Exceptione){
e.printStackTrace();
returnnull;
}
returninStream;
}
publicintdownLoad(Stringurl,StringlocalName,intlines)throwsFileNotFoundException,IOException{
FileOutputStreamfos=null;
InputStreaminStream=null;
intret=0;
try{
URLhttpurl=newURL(url);
URLConnectionconn=httpurl.openConnection();
inStream=conn.getInputStream();
fos=newFileOutputStream(localName);
byte[]b=newbyte[102400];
intj=0;
while(inStream.read(b)!=-1&&lines>0){
for(inti=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(Exceptione){
e.printStackTrace();
ret=-1;
}finally{
fos.close();
inStream.close();
returnret;
}
}
publicstaticvoidmain(String[]args){
Stringhttppath="";
intlines=0;
StringlocalName="";
try{
httppath=args[0];
localName=args[1];
lines=Integer.parseInt(args[2]);
}catch(Exceptione){
e.printStackTrace();
return;
}
try{
HttpUtilhu=newHttpUtil(httppath);
hu.downLoad(hu.getHttpPath(),localName,lines);
}catch(Exceptione){
e.printStackTrace();
}
}
}
这个工具实现了从HTTP服务器上下载指定行数的文件,并且不会因为编码的问题引起下载的文件内容乱码
三个工具已经搞定,下一次就是把这三个工具结合起来将HTTP、FTP的文件转移到HDFS上
hadoop工具
ftp工具
以上就是本文所述的全部内容了,希望大家能喜欢。
请您花一点时间将文章分享给您的朋友或者留下评论。我们将会由衷感谢您的支持!