我的应用程序将从我的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();
}
答案 0 :(得分:0)
如果您使用一个线程发送每个下载,我建议您使用,有几种可能性。
使用Future
和FutureTask
等待所有线程完成。
使用thread.join()
等待线程停止。