<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    athrunwang

    紀元
    數據加載中……
    canghailan 使用URLConnection下載文件
    package canghailan;

    import canghailan.util.StopWatch;

    import java.io.*;
    import java.net.URL;
    import java.net.URLConnection;
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;

    /**
     * User: canghailan
     * Date: 11-12-9
     * Time: 下午2:03
     */
    public class Downloader implements Callable<File> {
        protected int connectTimeout = 30 * 1000; // 連接超時:30s
        protected int readTimeout = 1 * 1000 * 1000; // IO超時:1min

        protected int speedRefreshInterval = 500; // 即時速度刷新最小間隔:500ms

        protected byte[] buffer;

        private URL url;
        private File file;

        private float averageSpeed;
        private float currentSpeed;

        public Downloader() {
            buffer = new byte[8 * 1024]; // IO緩沖區:8KB
        }

        public void setUrlAndFile(URL url, File file) {
            this.url = url;
            this.file = autoRenameIfExist(file);
            this.averageSpeed = 0;
            this.currentSpeed = 0;
        }

        public URL getUrl() {
            return url;
        }

        public File getFile() {
            return file;
        }

        public float getAverageSpeed() {
            return averageSpeed;
        }

        public float getCurrentSpeed() {
            return currentSpeed;
        }

        @Override
        public File call() throws Exception {
            StopWatch watch = new StopWatch();
            watch.start();

            InputStream in = null;
            OutputStream out = null;
            try {
                URLConnection conn = url.openConnection();
                conn.setConnectTimeout(connectTimeout);
                conn.setReadTimeout(readTimeout);
                conn.connect();

                in = conn.getInputStream();
                out = new FileOutputStream(file);

                int time = 0;
                int bytesInTime = 0;
                for (; ; ) {
                    watch.split();
                    int bytes = in.read(buffer);
                    if (bytes == -1) {
                        break;
                    }
                    out.write(buffer, 0, bytes);

                    time += watch.getTimeFromSplit();
                    if (time >= speedRefreshInterval) {
                        currentSpeed = getSpeed(bytesInTime, time);
                        time = 0;
                        bytesInTime = 0;
                    }
                }
            } catch (IOException e) {
                file.delete();
                throw e;
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                    }
                }
                if (out != null) {
                    try {
                        out.flush();
                        out.close();
                    } catch (IOException e) {
                    }
                }
            }

            watch.stop();
            averageSpeed = getSpeed(file.length(), watch.getTime());

            return file;
        }

        private static float getSpeed(long bytesInTime, long time) {
            return (float) bytesInTime / 1024 / ((float) time / 1000);
        }

        private static String getExtension(String string) {
            int lastDotIndex = string.lastIndexOf('.');
            // . ..
            if (lastDotIndex > 0) {
                return string.substring(lastDotIndex + 1);
            } else {
                return "";
            }
        }

        private static File autoRenameIfExist(File file) {
            if (file.exists()) {
                String path = file.getAbsolutePath();

                String extension = getExtension(path);
                int baseLength = path.length();
                if (extension.length() > 0) {
                    baseLength = path.length() - extension.length() - 1;
                }

                StringBuilder buffer = new StringBuilder(path);
                for (int index = 1; index < Integer.MAX_VALUE; ++index) {
                    buffer.setLength(baseLength);
                    buffer.append('(').append(index).append(')');
                    if (extension.length() > 0) {
                        buffer.append('.').append(extension);
                    }
                    file = new File(buffer.toString());
                    if (!file.exists()) {
                        break;
                    }
                }

            }
            return file;
        }

        public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {
            URL url = new URL("http://www.google.com.hk/");
            File file = new File("/home/canghailan/google.html");

            ExecutorService executorService = Executors.newSingleThreadExecutor();
            Downloader downloader = new Downloader();
            downloader.setUrlAndFile(url, file);
            File downloadFIle = executorService.submit(downloader).get();
            System.out.println("download " + downloadFIle.getName() +
                    " from " + url +
                    " @" + downloader.getAverageSpeed() + "KB/s");
        }
    }
    package canghailan.util;

    import java.util.concurrent.TimeUnit;

    /**
     * User: canghailan
     * Date: 11-12-9
     * Time: 下午3:45
     * <pre>
     * RUNNING:
     * startTime              split                        now
     * |<-   getSplitTime()   ->|<-   getTimeFromSplit()   ->|
     * |<-                   getTime()                     ->|
     * <pre/>
     * <pre>
     * STOPPED:
     * startTime                           stop            now
     * |<-           getTime()            ->|
     * <pre/>
     */
    public class StopWatch {
        private long startTime;
        private long stopTime;

        private State state;
        private boolean split;

        public StopWatch() {
            reset();
        }

        public void start() {
            if (state == State.UNSTARTED) {
                startTime = System.nanoTime();
                state = State.RUNNING;
                return;
            }
            throw new RuntimeException("Stopwatch already started or stopped.");
        }

        public void stop() {
            switch (state) {
                case RUNNING: {
                    stopTime = System.nanoTime();
                }
                case SUSPENDED: {
                    state = State.STOPPED;
                    split = false;
                    return;

                }
            }
            throw new RuntimeException("Stopwatch is not running.");
        }

        public void reset() {
            state = State.UNSTARTED;
            split = false;
        }

        public void split() {
            if (state == State.RUNNING) {
                stopTime = System.nanoTime();
                split = true;
                return;
            }
            throw new RuntimeException("Stopwatch is not running.");
        }

        public void suspend() {
            if (state == State.RUNNING) {
                stopTime = System.nanoTime();
                state = State.SUSPENDED;
                return;
            }
            throw new RuntimeException("Stopwatch must be running to suspend.");
        }

        public void resume() {
            if (state == State.SUSPENDED) {
                startTime += System.nanoTime() - stopTime;
                state = State.RUNNING;
                return;
            }
            throw new RuntimeException("Stopwatch must be suspended to resume.");
        }

        public long getTime() {
            return TimeUnit.NANOSECONDS.toMillis(getNanoTime());
        }

        public long getNanoTime() {
            switch (state) {
                case RUNNING: {
                    return System.nanoTime() - startTime;
                }
                case STOPPED:
                case SUSPENDED: {
                    return stopTime - startTime;
                }
                case UNSTARTED: {
                    return 0;
                }
            }
            throw new RuntimeException("Should never get here.");
        }

        public long getSplitTime() {
            return TimeUnit.NANOSECONDS.toMillis(getSplitNanoTime());
        }


        public long getSplitNanoTime() {
            if (split) {
                return stopTime - startTime;
            }
            throw new RuntimeException("Stopwatch must be running and split to get the split time.");
        }

        public long getTimeFromSplit() {
            return TimeUnit.NANOSECONDS.toMillis(getNanoTimeFromSplit());
        }

        public long getNanoTimeFromSplit() {
            if (state == State.RUNNING && split) {
                return System.nanoTime() - stopTime;
            }
            throw new RuntimeException("Stopwatch must be running and split to get the time from split.");
        }

        enum State {
            UNSTARTED,
            RUNNING,
            STOPPED,
            SUSPENDED
        }

    }

    posted on 2011-12-28 20:07 AthrunWang 閱讀(448) 評論(0)  編輯  收藏


    只有注冊用戶登錄后才能發表評論。


    網站導航:
     
    主站蜘蛛池模板: 亚洲一线产品二线产品| 亚洲va无码va在线va天堂| 亚洲最大成人网色香蕉| 精品福利一区二区三区免费视频| 亚洲AV无一区二区三区久久| 免费在线看黄的网站| 久久亚洲成a人片| 亚洲AV无码专区亚洲AV伊甸园| eeuss影院免费92242部| 亚洲线精品一区二区三区| 中文精品人人永久免费| 亚洲AV无码成人网站久久精品大| 永久免费av无码入口国语片| 久久91亚洲精品中文字幕| 69国产精品视频免费| 亚洲H在线播放在线观看H| 热99re久久精品精品免费| 朝桐光亚洲专区在线中文字幕 | www亚洲精品久久久乳| 亚洲无码黄色网址| 免费日本一区二区| 亚洲人成网站色在线观看| 噜噜嘿在线视频免费观看| 精品在线免费视频| 100000免费啪啪18免进| 国产精品亚洲综合久久| 国产免费人视频在线观看免费| 国内成人精品亚洲日本语音| 亚洲精品无码久久久影院相关影片| 91禁漫免费进入| 亚洲精品久久无码| 亚洲人成伊人成综合网久久久| 99热这里有免费国产精品| 亚洲综合在线一区二区三区| 亚洲乱码中文字幕综合234| 久久国产乱子伦精品免费不卡| 亚洲国产熟亚洲女视频| 国产AV无码专区亚洲AV漫画 | 无码国产精品久久一区免费| 美女被吸屁股免费网站| 亚洲av日韩av无码|