我正在创建一个 Java 应用程序。启动时,我的应用程序将下载所有必需的文件。我的应用程序将解析 XML 文件并从 XML 文件的 URL 下载文件。我希望我的应用程序“逐步”下载文件,所以我使用FutureTask
我的问题是,FutureTask
不适用于我的应用程序。
这是我的代码的一部分。
启动类
public void startDownloading()
{
Thread t = new Thread(new Runnable()
{
public void run()
{
downloader.startDownload();
}
});
t.run();
}
}
下载器类
private LibrariesDownloader ld;
private RDownloader rd;
public Downloader()
{
this.ld = new LibrariesDownloader(launcher);
this.rd = new RDownloader(launcher);
}
public void startDownload()
{
ExecutorService executor = Executors.newFixedThreadPool(2);
FutureTask<Void> libDownloader = new FutureTask<Void>(ld);
FutureTask<Void> resDownloader = new FutureTask<Void>(rd);
executor.execute(libDownloader);
if(libDownloader.isDone())
{
executor.execute(resDownloader);
}
}
LibrariesDownloader.class(& RDownloader.class(代码几乎一样,只是URL不同))
public class LibrariesDownloader implements Callable<Void>
{
private Proxy proxy = Proxy.NO_PROXY;
@Override
public Void call() throws Exception
{
try
{
URL resourceUrl = new URL("http://www.exmaple.com/libraries.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(resourceUrl.openConnection(proxy).getInputStream());
NodeList nodeLst = doc.getElementsByTagName("Content");
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();
final File path = new File("C://test/", key);
final String url = "http://www.exmaple.com/dl/" + key;
final String fileName = key;
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>()
{
@Override
protected Void doInBackground() throws Exception
{
try
{
URL fileURL = new URL(url);
org.apache.commons.io.FileUtils.copyURLToFile(fileURL, path);
}
catch(Exception e)
{
URL redownloadURL = new URL("http://www.example.com/dl/" + fileName);
File p = new File("C://test/", fileName);
org.apache.commons.io.FileUtils.copyURLToFile(redownloadURL, p);
}
return null;
}
@Override
public void done()
{
System.out.println(fileName + " had downloaded successfully");
}
};
worker.execute();
}
}
}
catch(Exception e)
{
launcher.println("An error was found when trying to download libraries file " + e);
}
return null;
}
}
<Key></Key>
我的 XML 文件中有很多。我的应用程序可以执行LibrariesDownloader
和下载所有库文件。下载完所有库文件后,我的应用程序就停在那里。它不会执行RDownloader
。
我的应用程序中有任何代码错误吗?谢谢你帮助我。