从java下载web url下载图像?

时间:2012-05-22 12:56:37

标签: java filenotfoundexception

URL url = new URL("http://localhost:8080/Work/images/abt.jpg");

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

FileOutputStream fos = new FileOutputStream("C://abt.jpg");
fos.write(response1);
fos.close();

在此代码中,最后3行有一些错误

  

SEVERE:servlet的Servlet.service()ImageDownloadServlet抛出了异常java.io. FileNotFoundException :C:/abt.jpg(没有这样的文件或目录)

我该如何解决?

5 个答案:

答案 0 :(得分:3)

可能会尝试将C:/abt.jpg切换为C:\\abt.jpg

答案 1 :(得分:3)

尝试使用File.pathSeparator而不是斜杠。

答案 2 :(得分:3)

String filePath = request.getParameter("action");
        System.out.println(filePath);
        // URL url = new
        // URL("http://localhost:8080/Works/images/abt.jpg");
        response.setContentType("image/jpeg");
        response.setHeader("Content-Disposition", "attachment; filename=icon" + ".jpg");
        URL url = new URL(filePath);
        URLConnection connection = url.openConnection();
        InputStream stream = connection.getInputStream();

        BufferedOutputStream outs = new BufferedOutputStream(response.getOutputStream());
        int len;
        byte[] buf = new byte[1024];
        while ((len = stream.read(buf)) > 0) {
            outs.write(buf, 0, len);
        }
        outs.close();
    }

答案 3 :(得分:2)

("C://abt.jpg");

尝试撤消斜杠

("C:\\abt.jpg");

我查了example link到FOS到C盘的例子,然后演示了另一种方法。

答案 4 :(得分:0)

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
                IOException, MalformedURLException {
        String filePath = request.getParameter("action");
        // String filename = "abt.jpg";
        System.out.println(filePath);
        URL url = new URL("http://localhost:8080/Works/images/abt.jpg");

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

        FileOutputStream fos = new FileOutputStream("/home/user/Downloads/abt.jpg");
        fos.write(response1);
        fos.close();

    }

此图片将位于下载文件夹