2012-03-29 41 views
1

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

下面是我用来使用WGET下载文件的代码。大约需要10分钟才能下载20 MB的文件。但是当我通过命令行运行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); 
} 

}

+0

没有缓冲输出流? – Jon 2012-03-29 09:52:13

回答

1

您已经阅读器缓存(好),但是你写的字符内容字符到磁盘(BAD)。这会杀死你的表现。这不是阅读,而是写作。

+0

啊...我看...有什么替代方法,你会建议加快? – manil 2012-03-29 09:42:26

+0

Thorbjørn有你的问题的解决方案:) – 2012-03-29 09:43:21

+0

雅,刚刚看到它..谢谢你们俩:) – manil 2012-03-29 09:44:21

4

用BufferedOutputStream包装FileOutputStream。

new BufferedOutputStream(new FileOutputStream(...))

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

+0

啊,这的确帮助..谢谢你Ravn :) – manil 2012-03-29 09:44:37

+0

但我的问题是,该文件需要5分钟通过代码下载..但是当我在命令行中使用wget下载文件时,相同的文件在4秒内下载!为什么是这样?? – manil 2012-03-29 09:47:36

+0

使用一个分析器,看看时间在哪里。 – 2012-03-29 09:52:15