13

ライブラリを使用してファイルをダウンロードし、保存されたバイト数を印刷するにはどうすればよいですか? 使ってみた

import static org.apache.commons.io.FileUtils.copyURLToFile;
public static void Download() {

        URL dl = null;
        File fl = null;
        try {
            fl = new File(System.getProperty("user.home").replace("\\", "/") + "/Desktop/Screenshots.zip");
            dl = new URL("http://ds-forums.com/kyle-tests/uploads/Screenshots.zip");
            copyURLToFile(dl, fl);
        } catch (Exception e) {
            System.out.println(e);
        }
    }

しかし、バイトや進行状況バーを表示できません。どの方法を使用すればよいですか?

public class download {
    public static void Download() {
        URL dl = null;
        File fl = null;
        String x = null;
        try {
            fl = new File(System.getProperty("user.home").replace("\\", "/") + "/Desktop/Screenshots.zip");
            dl = new URL("http://ds-forums.com/kyle-tests/uploads/Screenshots.zip");
            OutputStream os = new FileOutputStream(fl);
            InputStream is = dl.openStream();
            CountingOutputStream count = new CountingOutputStream(os);
            dl.openConnection().getHeaderField("Content-Length");
            IOUtils.copy(is, os);//begin transfer

            os.close();//close streams
            is.close();//^
        } catch (Exception e) {
            System.out.println(e);
        }
    }
4

2 に答える 2

13

ダウンロードする前に合計バイト数を取得する方法を探している場合はContent-Length、http応答のヘッダーからこの値を取得できます。

ダウンロード後の最終的なバイト数が必要な場合は、書き込んだファイルサイズを確認するのが最も簡単です。

ただし、ダウンロードされたバイト数の現在の進行状況を表示する場合は、apacheを拡張CountingOutputStreamしてラップするFileOutputStreamことで、writeメソッドが呼び出されるたびに通過するバイト数をカウントし、進行状況バーを更新することができます。

アップデート

これがの簡単な実装ですDownloadCountingOutputStream。使い方に慣れているかどうかはわかりActionListenerませんが、GUIを実装するのに便利なクラスです。

public class DownloadCountingOutputStream extends CountingOutputStream {

    private ActionListener listener = null;

    public DownloadCountingOutputStream(OutputStream out) {
        super(out);
    }

    public void setListener(ActionListener listener) {
        this.listener = listener;
    }

    @Override
    protected void afterWrite(int n) throws IOException {
        super.afterWrite(n);
        if (listener != null) {
            listener.actionPerformed(new ActionEvent(this, 0, null));
        }
    }

}

これは使用例です:

public class Downloader {

    private static class ProgressListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            // e.getSource() gives you the object of DownloadCountingOutputStream
            // because you set it in the overriden method, afterWrite().
            System.out.println("Downloaded bytes : " + ((DownloadCountingOutputStream) e.getSource()).getByteCount());
        }
    }

    public static void main(String[] args) {
        URL dl = null;
        File fl = null;
        String x = null;
        OutputStream os = null;
        InputStream is = null;
        ProgressListener progressListener = new ProgressListener();
        try {
            fl = new File(System.getProperty("user.home").replace("\\", "/") + "/Desktop/Screenshots.zip");
            dl = new URL("http://ds-forums.com/kyle-tests/uploads/Screenshots.zip");
            os = new FileOutputStream(fl);
            is = dl.openStream();

            DownloadCountingOutputStream dcount = new DownloadCountingOutputStream(os);
            dcount.setListener(progressListener);

            // this line give you the total length of source stream as a String.
            // you may want to convert to integer and store this value to
            // calculate percentage of the progression.
            dl.openConnection().getHeaderField("Content-Length");

            // begin transfer by writing to dcount, not os.
            IOUtils.copy(is, dcount);

        } catch (Exception e) {
            System.out.println(e);
        } finally {
            IOUtils.closeQuietly(os);
            IOUtils.closeQuietly(is);
        }
    }
}
于 2011-01-15T08:00:07.403 に答える
11

commons-ioにはIOUtils.copy(inputStream, outputStream). そう:

OutputStream os = new FileOutputStream(fl);
InputStream is = dl.openStream();

IOUtils.copy(is, os);

またIOUtils.toByteArray(is)、バイトを取得するために使用できます。

合計バイト数を取得することは別の話です。ストリームは合計を提供しません。ストリームで現在利用可能なもののみを提供できます。しかし、これはストリームなので、さらに多くのことが来る可能性があります。

そのため、http には合計バイト数を指定する特別な方法があります。応答ヘッダーにありContent-Lengthます。したがって、オブジェクトをurl.openConnection()呼び出してから呼び出す必要があります。バイト数を文字列として返します。次に使用すると、合計が得られます。getHeaderField("Content-Length")URLConnectionInteger.parseInt(bytesString)

于 2011-01-15T07:43:03.213 に答える