0

我试图从网站中的链接保存图像我已经编写了这段代码,但这不起作用..请帮助我做到这一点

public void imageshow(String linkText) {

    try {

        URL url = new URL(linkText);
        InputStream in = new BufferedInputStream(url.openStream());
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buf = new byte[4 * 1024];
        int n = 0;
        while (-1 != (n = in.read(buf))) {
            out.write(buf, 0, n);
        }
        out.close();
        in.close();
        byte[] response = out.toByteArray();

        FileOutputStream fos = new FileOutputStream("C://chart.gif");

        fos.write(response);
        fos.close();

    } catch (Exception e) {
    }

}
4

1 回答 1

0

取自这里

import java.net.*;
import java.io.*;

public class DownloadFile
{
  public static void main(String[] args)
  {
     try
     {
        /*
         * Get a connection to the URL and start up
         * a buffered reader.
         */
        long startTime = System.currentTimeMillis();

        System.out.println("Connecting to Mura site...\n");

        URL url = new URL("http://www.getmura.com/currentversion/");
        url.openConnection();
        InputStream reader = url.openStream();

        /*
         * Setup a buffered file writer to write
         * out what we read from the website.
         */
        FileOutputStream writer = new FileOutputStream("C:/mura-newest.zip");
        byte[] buffer = new byte[153600];
        int totalBytesRead = 0;
        int bytesRead = 0;

        System.out.println("Reading ZIP file 150KB blocks at a time.\n");

        while ((bytesRead = reader.read(buffer)) > 0)
        {  
           writer.write(buffer, 0, bytesRead);
           buffer = new byte[153600];
           totalBytesRead += bytesRead;
        }

        long endTime = System.currentTimeMillis();

        System.out.println("Done. " + (new Integer(totalBytesRead).toString()) + " bytes read (" + (new Long(endTime - startTime).toString()) + " millseconds).\n");
        writer.close();
        reader.close();
     }
     catch (MalformedURLException e)
     {
        e.printStackTrace();
     }
     catch (IOException e)
     {
        e.printStackTrace();
     }

  }

}
于 2012-06-06T13:30:24.417 回答