用java从web url下载图像?
在这段代码的最后3行中有一些错误 严重:Servlet ImageDownloadServlet的Servlet.service()抛出异常java.io。FileNotFoundException:C:/abt.jpg(没有这样的文件或目录)用java从web url下载图像?,java,filenotfoundexception,Java,Filenotfoundexception,在这段代码的最后3行中有一些错误 严重:Servlet ImageDownloadServlet的Servlet.service()抛出异常java.io。FileNotFoundException:C:/abt.jpg(没有这样的文件或目录) 我该怎么解决呢?也许可以尝试将C:/abt.jpg切换到C:\\abt.jpg(“C://abt.jpg”) 试着把斜线颠倒过来 (“C:\\abt.jpg”) 我查阅了一个FOS到C驱动器的示例,演示中的情况正好相反。尝试使用File.pathsept
我该怎么解决呢?也许可以尝试将
C:/abt.jpg
切换到C:\\abt.jpg
(“C://abt.jpg”)代码>
试着把斜线颠倒过来
(“C:\\abt.jpg”)代码>
我查阅了一个FOS到C驱动器的示例,演示中的情况正好相反。尝试使用File.pathseptor而不是斜杠
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();
此图像将位于Windows系统的下载文件夹中,至少在基于NT(即Windows NT、XP、Vista和7)的系统中,正斜杠(“/”)是一个有效的文件路径组件分隔符,可以用来代替正式的反斜杠(\”)。但是,正斜杠不需要转义。在Windows系统上,至少在基于NT(即Windows NT、XP、Vista和7)的系统上,正斜杠(“/”)是有效的文件路径组件分隔符,可以用来代替正式的反斜杠(\”)。但是,正斜杠不需要转义。经过测试,您是对的。奇怪的是,它是双向的。(“//”和“/”)
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();
}
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();
}