Java 零字节文件

Java 零字节文件,java,Java,当尝试使用线程从url下载多个具有不同查询的文件时,文件未正确写入或生成0字节文件,或者某些文件未打开。代码如下所示。请帮帮我,伙计们 public void run() { try { HttpURLConnection conn = null; URL url = new URL(strUrl); conn = (HttpURLConnection) url.openConnection(); conn.setIns

当尝试使用线程从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();
    }
}

请发布一个。检查重定向连接的返回代码。这可能不是你所期望的。你收到了什么日志消息。我可以想出很多原因,为什么你可能会得到零长度的文件。。。或者什么都没有。日志消息和其他输出将告诉您很多。顺便说一句,将编写内容写入标准输出与日志记录相结合是个坏主意。strUrl是查询url,它被重定向到另一个url以下载pdf文件。Upto InputStream is=conn.getInputStream();工作正常。但写作部分给出了问题所在。