无为

无为则可为,无为则至深!

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  190 Posts :: 291 Stories :: 258 Comments :: 0 Trackbacks
我刚学java不久,写了这个程序,小试身手各位有什么改进的地方,请赐教,

import java.net.*;
import java.io.*;
import java.lang.*;

public class down {
    public static void main(String[] args) throws Exception {
        if(args.length==0){
                System.out.println("Usage: down <url>");
                System.exit(1);
        }
        URL yahoo = new URL(args[0]);
        String name = args[0].substring(args[0].lastIndexOf("/")+1); 
        HttpURLConnection connection = (HttpURLConnection)yahoo.openConnection(); ;

        
        File writeF = new File(name);
        RandomAccessFile file=new RandomAccessFile(writeF,"rw");
        
        byte[] b = new byte[1024];
        int nRead;
        long down_length;
        if(writeF.exists()){
            down_length = writeF.length();
            file.seek(down_length);
        }else{
            down_length = 0;
        }   
        connection.setRequestProperty("User-Agent","NetFox");
        connection.setRequestProperty("RANGE","bytes="+down_length+"-");
        DataInputStream in = new DataInputStream(connection.getInputStream());
        String strLength = connection.getHeaderField("Content-Length");
        long length = Long.parseLong(strLength);
        System.out.println(name +" length: "+strLength);
        if(connection.getHeaderField("Content-Range") != null )
            System.out.println("Download :"+connection.getHeaderField("Content-Range")); 
        
        int down=0;
        int flag =0;    
        System.out.print(down_length/1024+"K\t->");
        while ((nRead=in.read(b,0,b.length)) > 0){
            file.write(b,0,nRead);
            down = down +nRead;
            if(down >= 1024){
                down = down -1024;
                flag++;
                System.out.print(".");
                if(flag%10 == 0) System.out.print(" ");
                if(flag%50 == 0) {
                      down_length = down_length+1024*50;
                      int per = (int)(((double)down_length/(double)length)*100);
                      System.out.println("["+per+"%]");
                      System.out.print(down_length/1024+"K\t->");
                }
            }               
            //in.flush();
        }
        System.out.println("\nFinished!");
        in.close();
        file.close();
    }
}


凡是有该标志的文章,都是该blog博主Caoer(草儿)原创,凡是索引、收藏
、转载请注明来处和原文作者。非常感谢。

posted on 2005-12-14 13:08 草儿 阅读(546) 评论(0)  编辑  收藏 所属分类: Java编程经验谈

只有注册用户登录后才能发表评论。


网站导航: