我正在創建一個將從URL(我自己的FTP服務器)下載文件的應用程序。問題是,當我點擊「下載」按鈕時,我的應用程序將開始下載,但是我的應用程序在下載時沒有任何響應,但是在下載完成後一切正常。Java - 如何從URL下載文件
這裏是我的代碼
某些部分GUI.class
b_Download.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
String username = "Test";
startDownloading(username);
}
});
private void startDownload(String username)
{
downloader.println("Welcome " + username); //println will show text in a textpane(GUI) and console
downloader.startDownloading();
}
Downloader.class
public void startDownloading()
{
println("Download jobs started");
download.downloadLIB();
}
DownloadJob.class
public void downloadLIB()
{
launcher.println("Start downloading files from server...");
String libURL = "http://www.example.com/file.jar";
File libFile = new File("C://file.jar");
downloadFile(libURL, libFile, "file.jar");
}
public void downloadFile(String url, File path, String fileName)
{
InputStream in = null;
FileOutputStream fout = null;
try
{
in = URI.create(url).toURL().openStream();
fout = new FileOutputStream(path);
byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1)
{
fout.write(data, 0, count);
}
}
catch(Exception e)
{
launcher.println("Cannot download file : " + fileName, e);
}
finally
{
if (in != null)
try
{
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
if(fout != null)
try
{
fout.close();
}
catch (IOException e)
{
e.printStackTrace();
}
launcher.println("File " + fileName + " downloaded successfully");
}
}
當我按下「下載'按鈕,m y textpane顯示單詞「歡迎用戶名」,那麼它沒有任何迴應。但是我的控制檯會顯示「歡迎用戶名」,「下載作業開始」以及「從服務器開始下載文件...」。幾分鐘後(文件下載完成時,我的應用程序將開始再次有反應...
在[併發在Swing(HTTP看看://文檔.oracle.com/javase/tutorial/uiswing/concurrency /)並注意關於SwingWorker的部分 – MadProgrammer