我正在使用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);
}
}
沒有緩衝輸出流? – Jon 2012-03-29 09:52:13