-2

我的应用程序将从我的 Web 服务器解析一个 XML 文件,然后下载这些文件。我的应用程序将从 XML 文件中获取“URL”的内容并使用 Common-IO 的 FileUtils 下载它。我的问题是,我怎么知道我的下载过程是否完成。我的 XML 文件中有很多“URL”。

这是我的代码的一部分:

private Proxy proxy = Proxy.NO_PROXY;
    public void downloadLibrary()
        {
            System.out.println("Start downloading libraries from server...");
            try
            {
                URL resourceUrl = new URL("http://www.example.com/libraries.xml");
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                Document doc = db.parse(resourceUrl.openConnection(proxy).getInputStream());
                NodeList nodeLst = doc.getElementsByTagName("Contents");
                for (int i = 0; i < nodeLst.getLength(); i++)
                {
                    Node node = nodeLst.item(i);

                    if (node.getNodeType() == 1)
                    {
                        Element element = (Element)node;
                        String key = element.getElementsByTagName("Key").item(0).getChildNodes().item(0).getNodeValue();
                        File f = new File(launcher.getWorkingDirectory(), key);
                        downloadFile("http://www.example.com/" + key, f, "libraries");
                    }
                }
            }
            catch(Exception e)
            {
                System.out.println("Error was found when trying to download libraries file " + e);
            }

        }

        public void downloadFile(final String url, final File path, final String fileName)
        {
            SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>()
            {
                @Override
                protected Void doInBackground() throws Exception
                {
                    launcher.println("Downloading file " + fileName + "...");
                    try
                    {
                        URL fileURL = new URL(url);
                        ReadableByteChannel rbc = Channels.newChannel(fileURL.openStream());
                        FileOutputStream fos = new FileOutputStream(path);
                        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
                    }
                    catch(Exception e)
                    {
                        System.out.println("Cannot download file : " + fileName + " " + e);
                    }
                    return null;
                }
                @Override
                public void done()
                {
                    System.out.println(fileName + " had downloaded sucessfully");

                }
            };
            worker.execute();
        }
4

1 回答 1

0

如果您使用一个线程发送每个下载,我建议您这样做,您有多种可能性。

使用FutureandFutureTask等待所有线程完成。

用于thread.join()等待线程停止。

于 2013-10-03T15:38:13.797 回答