日期:2014-05-20  浏览次数:20995 次

如何用java获取网络文件的大小
如题
还有就是如何用多线程序下载文件
最好有代码解释

------解决方案--------------------
dream!

------解决方案--------------------
mark~
------解决方案--------------------
String length = httpUrl.getHeaderField( "Content-Length "); //获取文件长度
------解决方案--------------------
我写的多线程文件下载程序
public class DownloadNetTest {
private File fileOut;
private URL url;
private long fileLength=0;
//初始化线程数
private int ThreadNum=5;

public DownloadNetTest(){
try{
System.out.println( "正在链接URL ");
url=new URL( "http://211.64.201.201/uploadfile/nyz.mp3 ");
HttpURLConnection urlcon=(HttpURLConnection)url.openConnection();
//根据响应获取文件大小
fileLength=urlcon.getContentLength();
if(urlcon.getResponseCode()> =400){
System.out.println( "服务器响应错误 ");
System.exit(-1);
}
if(fileLength <=0)
System.out.println( "无法获知文件大小 ");
//打印信息
printMIME(urlcon);
System.out.println( "文件大小为 "+fileLength/1024+ "K ");
//获取文件名
String trueurl=urlcon.getURL().toString();
String filename=trueurl.substring(trueurl.lastIndexOf( '/ ')+1);
fileOut=new File( "D:// ",filename);
}
catch(MalformedURLException e){
System.err.println(e);
}
catch(IOException e){
System.err.println(e);
}
init();
}
private void init(){
DownloadNetThread [] down=new DownloadNetThread[ThreadNum];
try {
for(int i=0;i <ThreadNum;i++){
RandomAccessFile randOut=new RandomAccessFile(fileOut, "rw ");
randOut.setLength(fileLength);
long block=fileLength/ThreadNum+1;
randOut.seek(block*i);
down[i]=new DownloadNetThread(url,randOut,block,i+1);
down[i].setPriority(7);
down[i].start();
}
//循环判断是否下载完毕
boolean flag=true;
while (flag) {
Thread.sleep(500);
flag = false;
for (int i = 0; i < ThreadNum; i++)
if (!down[i].isFinished()) {
flag = true;
break;
}
}// end while
System.out.println( "文件下载完毕,保存在 "+fileOut.getPath() );
} catch (FileNotFoundException e) {
System.err.println(e);
e.printStackTrace();
}
catch(IOException e){
System.err.println(e);
e.printStackTrace();
}
catch (InterruptedException e) {
System.err.println(e);
}

}
private void printMIME(HttpURLConnection http){
for(int i=0;;i++){
String mine=http.getHeaderField(i);
if(mine==null)
return;
System.out.println(http.getHeaderFieldKey(i)+ ": "+mine);
}
}

public static void main(String[] args) {
DownloadNetTest app=new DownloadNetTest();
}

}


//线程类
public class DownloadNetThread extends Thread{
private InputStream randIn;
private RandomAccessFile randOut;
private URL url;
private long block;
private int threadId=-1;
private boolean done=false;

public DownloadNetThread(URL url,RandomAccessFile out,long block,int threadId){