此博文为原创技术分享,如需转载请标明出处
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public static void main(String[] args) {
String netImagePath = "https://avatar.csdnimg.cn/8/E/9/1_qq_36911145.jpg";
String path = "D://var/";
String fileName = "test1.jpg";
InputStream is = null;
FileOutputStream out = null;
try {
URL url = new URL(netImagePath);
byte[] by = new byte[1024];
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(50000);
is = conn.getInputStream();
String picPath = path + fileName;
out = new FileOutputStream(picPath);
int len = -1;
while ((len = is.read(by)) != -1) {
out.write(by, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}