通过命令行执行WGET下载更快,而通过Java代码执行时下载速度慢

时间:2012-03-29 09:38:19

标签: java wget

我正在使用WGET通过java代码下载文件,这需要大约10分钟来下载20 MB文件。但是在通过命令行执行 wget 下载时,同样的文件会以10MbPs的速度在7秒内下载。有人知道为什么吗?如何改进我的Java代码?

以下是我用WGET下载文件的代码。下载20 MB文件大约需要10分钟。但是当我通过命令行运行wget命令时,它会在几秒钟内发生!!

  import java.io.BufferedReader;
  import java.io.File;
  import java.io.FileOutputStream;
  import java.io.IOException;
  import java.io.InputStreamReader;
  import java.net.MalformedURLException;
  import java.net.URL;
  import java.net.URLConnection;



 public class WGETServer
{



public File download(URL sourceurl, String username, String password, String fileName)
{
    //System.out.println("WGET download() is starting ...");

    File file = null;
    URLConnection urlConnection = null;
    BufferedReader reader = null;
    FileOutputStream outputStream = null;
    try {

        urlConnection = sourceurl.openConnection();

            String userNameAndPassword = username +":"+ password;
            String encoding = new sun.misc.BASE64Encoder().encode (userNameAndPassword.getBytes());
            //The line which is supposed to add authorization data 
            urlConnection.setRequestProperty ("Authorization", "Basic " + encoding);

        reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
    }
    catch (IOException e) {
        System.err.println("Internet connection failure or invalid Username/Password.");
        return null;
    }
    try {
        file = new File("file path");
        outputStream = new FileOutputStream(file);
        int character;
        while((character = reader.read()) != -1)
        {
            outputStream.write(character);
        } 
        outputStream.flush();
        outputStream.close();
        reader.close();
    } catch (IOException e) {
        System.err.println(e.getMessage());
        return null;
    }
    System.out.println("downloading completed");
    return file;

}



public static void main(String args[]) throws MalformedURLException
{
    URL sourceurl = new URL("https:blablabla");
    String username = "username";
    String password = "password";
    String filename = "filename";
    WGETServer WGETdownload = new WGETServer();
    WGETdownload.download(sourceurl, username, password, filename);
}

}

2 个答案:

答案 0 :(得分:4)

使用BufferedOutputStream包装FileOutputStream。

new BufferedOutputStream(new FileOutputStream(...))

否则,所写的每个字符都由底层操作系统同步到磁盘,这是一个耗时的过程。这就是缓冲非常重要的原因。

答案 1 :(得分:1)

你有缓冲读卡器(好),但是你把char的内容写入磁盘(BAD)。这会杀死你的表现。这不是阅读,而是写作。