您的位置:首页 > 其它

2014/03/28 从指定网址下载数据并保存

2014-03-28 21:23 281 查看
从指定网址下载数据并保存,用两个线程分别下载

代码的思路是创建两个线程,分别将网址传递给ur方法,调用ur方法从指定网址获得数据流,ur将数据信息交给fil和input方法完成文件才创建和数据的保存

再调用jx类中的方法实现文件的解析和保存(jx还没有实现)

import java.io.*;

import java.net.*;

public class Xz {

public static Thread x1;

public static Thread x2;

public String fileName;

public static void main(String[] args) {

Thread x1 = new Thread(){

String strUrl = "http://192.168.0.101:7000/hfs";

int numb = 1;

public void run(){

Ur(strUrl , numb);//调用ur方法

}

}; x1.start();

Thread x2 = new Thread(){

String strUrl = "http://192.168.0.101:7000/ww.txt";

int numb = 2;

public void run(){

Ur(strUrl , numb);//调用ur方法

}

}; x2.start();

//Jx.qwe(); //调用此类读取文件然后解析xml和json,暂时还没有实现

}

public static void Ur(String strUrl,int numb){

try{

URL url = new URL(strUrl); //创建URL对象,创建shuj连接到指定网址

HttpURLConnection shuj = (HttpURLConnection)url.openConnection();

InputStream inStream = shuj.getInputStream();//通过输入流获取文件数据

byte[] btImg = input(inStream);//得到文件的数据

if(numb == 1){

String fileName = "hfs.exe";

fil(fileName,numb,btImg);}//创建文件

else{

String fileName = "ww.txt";

fil(fileName,numb,btImg);

}

}catch (Exception e) {

e.printStackTrace();

}

}

public static void fil(String fileName ,int numb , byte[] btImg){

try {

File file = new File("D:\\" + fileName);//指定文件路径和名称

FileOutputStream fops = new FileOutputStream(file);

fops.write(btImg);

fops.flush();

fops.close();

System.out.println("文件"+numb+"已经写入到d盘");

} catch (Exception e) {

e.printStackTrace();

}

}

public static byte[] input(InputStream inStream) throws Exception{

ByteArrayOutputStream outStream = new ByteArrayOutputStream();

byte[] buffer = new byte[1024];

int len = 0;

while( (len=inStream.read(buffer)) != -1 ){

outStream.write(buffer, 0, len);

}

inStream.close();

return outStream.toByteArray();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: