我有一个用于html页面下载的功能。
这是代码:

public class pageDownload {
    public static void down(final String filename, final String urlString)
            throws MalformedURLException, IOException {
        BufferedInputStream in = null;
        FileOutputStream fout = null;
        try {
            in = new BufferedInputStream(new URL(urlString).openStream());
            fout = new FileOutputStream(new File(filename));
            final byte data[] = new byte[1024];
            int count;
            while ((count = in.read(data, 0, 1024)) != -1) {
                fout.write(data, 0, count);
            }
        } catch (IOException e) {
            System.err.println("Caught IOException: " + e.getMessage());
        } catch (IndexOutOfBoundsException e) {
            System.err.println("IndexOutOfBoundsException: " + e.getMessage());
        }
        in.close();
        fout.close();
    }
}

可以正常工作,当我尝试下载不存在的页面时出现问题。在这种情况下,我不知道如何处理404错误。
有人知道吗?

最佳答案

你的意思是这样吗?我添加了一个finally以保存关闭流

public class pageDownload {
    public static void down(final String filename, final String urlString)
    throws MalformedURLException, IOException {

        BufferedInputStream in = null;
        FileOutputStream fout = null;
        try {
            in = new BufferedInputStream(new URL(urlString).openStream());
            fout = new FileOutputStream(new File(filename));

            final byte data[] = new byte[1024];
            int count;
            while ((count = in.read(data, 0, 1024)) != -1) {
                fout.write(data, 0, count);
            }
        } catch(FileNotFoundException ex)
        {
            System.err.println("Caught 404: " + e.getMessage());
        }
        catch(IOException ex)
        {
            System.err.println("Caught IOException: " + e.getMessage());
        }
        catch(IndexOutOfBoundsException e)
        {
            System.err.println("IndexOutOfBoundsException: " + e.getMessage());
        }
        finally{
            if(in != null)
                try { in.close(); } catch ( IOException e ) { }
            if(fout != null)
                try { fout.close(); } catch ( IOException e ) { }
        }
    }
}

07-28 07:06