java編寫Http辦事器下載對象。本站提示廣大學習愛好者:(java編寫Http辦事器下載對象)文章只能為提供參考,不一定能成為您想要的結果。以下是java編寫Http辦事器下載對象正文
這個對象比擬簡略,用於合營別的一個對象停止文件傳送,空話少說,上代碼
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對象
以上就是本文所述的全體內容了,願望年夜家能愛好。
請您花一點時光將文章分享給您的同伙或許留下評論。我們將會由衷感激您的支撐!