JAVA 从网络下载图片保存到电脑(亲测有用)

JAVA 从网络下载图片保存到电脑

我尝试了网上很多人的方法

			while ((a=inputStream.read())!=-1) {//这个是大家普遍用的方法
					fileOutputStream.write(b, 0, a);//这里b是byte[],a是length
				}

查了很多资料,都没有用,最后看了一下输入流的方法read。原来。。。。

			while ((a=inputStream.read(b,0,b.length))!=-1) {//这样子就行了
							fileOutputStream.write(b, 0, a);
				}

直接上代码

  • 这里要先注意你的url是正确的图片地址,类似.jpg或者.png之类的地址,不然怎么改代码都会失败
//第一个参数是图片的URL网络地址,第二个是你要保存到电脑的路径
public static void DownaloadPhoto(String url,String downaload_path){
			try {
				HttpURLConnection connection=(HttpURLConnection) new URL(url).openConnection();//开启网络	
				InputStream inputStream=connection.getInputStream();//获取输入流
				FileOutputStream fileOutputStream=new FileOutputStream(new File(downaload_path));//输出流
				
				byte[] b=new byte[1024];
				int a=0;
				while ((a=inputStream.read(b,0,b.length))!=-1) {//-1就是读取完毕的值
					fileOutputStream.write(b, 0, a);//写入数据
				}
				fileOutputStream.close();//记得关闭
				inputStream.close();
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

	}

}

博主已经试过了,是正确的代码,也成功下载了网上的图片

很简单的一段代码,但是对于我这种小白却是一个大坑。。。

哪里不对的欢迎大家斧正qwq。

发布了4 篇原创文章 · 获赞 5 · 访问量 322

猜你喜欢

转载自blog.csdn.net/qq_31254489/article/details/97963159