零字节文件

时间:2017-01-25 06:31:13

标签: java

当尝试使用不同的查询从url下载多个文件时使用线程文件没有正确写入或生成0字节文件或某些文件没有打开。代码如下。请帮帮我们......

public void run() {

    try {
        HttpURLConnection conn = null;
        URL url = new URL(strUrl);

        conn = (HttpURLConnection) url.openConnection();
        conn.setInstanceFollowRedirects(false);

        int code = conn.getResponseCode();
        if (code == 400) {
            LOGGER.info("Response Status:" + strUrl);
        } else if (code == 302 || code == 304) {
            LOGGER.info("Redirected 302: " + strUrl);
            String newUrl = conn.getHeaderField("Location");
            newUrl = newUrl.replace(".html", "");


            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            URL website = new URL(newUrl);
            conn = (HttpURLConnection) website.openConnection();

            InputStream is = conn.getInputStream();

            FileOutputStream fos = new FileOutputStream(destination);

            byte[] buffer = new byte[4096];
            int bytesRead = 0;

            while ((bytesRead = is.read(buffer)) > -1)
                fos.write(buffer, 0, bytesRead);

            fos.close();
            is.close();

        } else {
            LOGGER.error(conn.getResponseCode() + ":  " + strUrl);
        }
    } catch (java.net.SocketTimeoutException e) {
        e.printStackTrace();
        LOGGER.error("Connection Time out " + strUrl);
        System.out.println("Connection Time out " + strUrl);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

0 个答案:

没有答案