如何在不冻结应用程序GUI的情况下下载文件

时间:2013-09-29 07:38:14

标签: java swing download

我正在创建一个从URL(我自己的FTP服务器)下载文件的应用程序。问题是,当我点击“下载”按钮时,我的应用程序将开始下载,但我的应用程序在下载时没有任何响应,但在下载后一切正常。

以下是我的代码的一部分

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");
        }
    }

当我按下“下载”按钮时,我的textpane显示“欢迎用户名”这个词,然后它没有回复。但我的控制台将显示“欢迎用户名”,“下载作业已启动”和“从服务器开始下载文件......”。几分钟后(文件完成下载后,我的应用程序将再次开始响应......

2 个答案:

答案 0 :(得分:0)

您需要生成新的Thread

当您向网络发送请求时,您执行一段代码将挂起,直到它获取它正在寻找的内容,即服务器。这意味着应用程序主线程将不会响应系统消息,导致系统认为它已停止响应。

解决方法是生成工作线程,或者运行服务来处理网络请求。

线程将在等待服务器时挂起,而主活动线程可以继续与用户进行交互。

当工作线程完成其任务时,您需要回调主线程以提醒用户下载进度/完成。

答案 1 :(得分:0)

Swing是一个单线程框架。也就是说,所有交互和修改都应在Event Dispatching Thread的上下文中执行。

任何阻止此线程的东西都会阻止它处理新事件,包括绘制请求。

这会让你受到约束。执行下载而不是“冻结”程序的唯一方法是在某种后台线程中运行,但是你不能从这个线程更新或修改,因为这必须在EDT的上下文中完成。 / p>

虽然有很多方法可以解决这个问题,但最简单的方法可能就是使用SwingWorker

它有能力在后台运行(在EDT之外),重新同步EDT更新的方法(publishprocessdone)并在构建中提供报告进度的功能。

例如......

请查看Concurrency in Swing了解更多详情......