我正在使用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);
}
}
2012-03-29
manil
+0
没有缓冲输出流? –
2012-03-29 09:52:13