2

自分の Web サーバーから大量のファイルをダウンロードするアプリケーションを作成しています。しかし、なぜそれが機能していないのですか。何の反応もありません..

ここに私のコードの一部があります

Downloader.class

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/

独自のダウンローダーを構築する必要なく、Web サイトからドキュメントを消費するのに役立つ場合があります。

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 に答える