2

我正在创建一个应用程序,它将从我自己的 Web 服务器下载大量文件。但是我知道为什么它不起作用。它没有任何反应..

这是我的代码的一部分

下载器类

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

这是我的 xml 文件的一部分(libraries.xml)

<Key>libraries/org/lwjgl/lwjgl/lwjgl/2.9.0/lwjgl-2.9.0.jar</Key>

我的想法是,我的应用程序将读取 XML 文件。然后它将从服务器下载文件并保存到计算机。例如,我的应用程序下载http://www.example.com/libraries/org/lwjgl/lwjgl/lwjgl/2.9.0/lwjgl-2.9.0.jar然后它将保存到我的 XML 文件中C://WorkingDir/libraries/org/lwjgl/lwjgl/lwjgl/2.9.0/lwjgl-2.9.0.jar 有大量的内容<Key></Key>,我必须下载所有内容。

那有什么代码错了吗?感谢您的帮助。

4

1 回答 1

1

首先尝试通过某种阅读器直接使用与字符串的连接,然后您可以根据需要进行操作。

package come.somecompany.somepackage.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class WebUtils {

    /**
     * Gets the HTML value of a website and
     * returns as a string value.
     * 
     * @param website website url to get.
     * @param ssl True if website is SSL.
     * @param useragent Specified User-Agent (empty string "" means use system default).
     * @return String value of website.
     */
    public String getHTML(String website, boolean ssl, String useragent) {
        String html = "";
        String temp;
        String prefix;
        if (ssl) {
            prefix = "https://";
        } else {
            prefix = "http://";
        }
        try {
            URL url = new URL(prefix + website);
            URLConnection con = url.openConnection();
        if (!(useragent.equalsIgnoreCase(""))) {
            con.setRequestProperty("User-Agent", useragent);
        }
        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        while((temp = in.readLine()) != null) {
            html += temp + "\n";
        }
        in.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return html;
    }
}

此外,看起来您正在尝试使用 XML 模式解析 HTML ......这可能会给您带来困难。你可以试试 JSoup——它是一个 java HTML 解析器,工作得很好而且很简单:http: //jsoup.org/

它可能有助于从您的网站使用文档,而无需构建您自己的下载器。

UPDATE --

尝试读入BufferedReader,也许您的程序没有接收到完整的文档,缓冲阅读器可能会有所帮助。

BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));

因此,使用您的第一种方法,例如:

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();

            // change here
            URLConnection con = resourceUrl.openConnection();
            BufferedReader bfr = new BufferedReader(new InputStreamReader(con.getInputStream()));

            String tempDoc = "";
            String tempStr;
            while (tempStr = bfr.readLine()) != null) {
                tempDoc += tempStr + System.getProperty("line.separator");
            }

            Document doc = db.parse(tempDoc);

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

    }
于 2013-10-01T15:15:05.023 回答