java編寫Http服務器下載工具
更新時間:2015年03月25日 15:39:28 投稿:hebedich
這篇文章主要介紹了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();
}
}
}
這個工具實現(xiàn)了從HTTP服務器上下載指定行數(shù)的文件,并且不會因為編碼的問題引起下載的文件內(nèi)容亂碼
三個工具已經(jīng)搞定,下一次就是把這三個工具結(jié)合起來將HTTP、FTP的文件轉(zhuǎn)移到HDFS上
以上就是本文所述的全部內(nèi)容了,希望大家能喜歡。
請您花一點時間將文章分享給您的朋友或者留下評論。我們將會由衷感謝您的支持!
相關(guān)文章
Java并發(fā)容器之ConcurrentLinkedQueue詳解
這篇文章主要介紹了Java并發(fā)容器之ConcurrentLinkedQueue詳解,加鎖隊列的實現(xiàn)較為簡單,這里就略過,我們來重點來解讀一下非阻塞隊列,2023-12-12
從點到面, 下面我們來看下非阻塞隊列經(jīng)典實現(xiàn)類ConcurrentLinkedQueue,需要的朋友可以參考下
SpringCloud Config使用本地倉庫及map注入
這篇文章主要介紹了SpringCloud Config使用本地倉庫及map注入,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-09-09
SpringCloud使用Nacos保存和讀取變量的配置方法
在使用SpringCloud開發(fā)微服務時,經(jīng)常會遇到一些比較小的后臺參數(shù)配置,這些配置不足以單獨開一張表去存儲,而且其他服務會讀取該參數(shù),這篇文章主要介紹了SpringCloud使用Nacos保存和讀取變量,需要的朋友可以參考下2022-07-07

