Open Admol opened 8 years ago
public static void main(String[] args) throws IOException { String jsonUrl = "https://raw.githubusercontent.com/spacelan/wechat-emoticon/master/emoticons.json"; URL url = new URL(jsonUrl); InputStream is = url.openConnection().getInputStream(); InputStreamReader isr = new InputStreamReader(is, "utf-8"); BufferedReader br = new BufferedReader(isr); String line = ""; String json = ""; while ((line = br.readLine()) != null) { json += line; } System.out.println(json); isr.close(); is.close(); JSONArray ja = JSONArray.parseArray(json);
FileOutputStream fileOutputStream = null; DataInputStream dis = null; System.out.println("预计下载图片数count=" + ja.size()); for (int i = 0; i < ja.size(); i++) { JSONObject jo = (JSONObject) ja.get(i); URL imgUrl = new URL((String) jo.get("url")); byte[] buffer = new byte[1024]; dis = new DataInputStream(imgUrl.openConnection().getInputStream()); File file = new File("d://wechat//img_" + i + ".gif"); fileOutputStream = new FileOutputStream(file); int len = 0; System.out.println("正在下载第"+i+"张图片............"); while ((len = dis.read(buffer)) > 0) { fileOutputStream.write(buffer, 0, len); } } fileOutputStream.close(); dis.close(); }
你们简直是666🌚
不建议在循环中使用字符串"+",虽然编译器优化后会把"+"操作转化成StringBuilder的append()操作,但是在循环中会生成多个Stringbuilder,影响性能
在for里不try catch遇到图片不存在的会崩……
public static void main(String[] args) throws IOException { String jsonUrl = "https://raw.githubusercontent.com/spacelan/wechat-emoticon/master/emoticons.json"; URL url = new URL(jsonUrl); InputStream is = url.openConnection().getInputStream(); InputStreamReader isr = new InputStreamReader(is, "utf-8"); BufferedReader br = new BufferedReader(isr); String line = ""; String json = ""; while ((line = br.readLine()) != null) { json += line; } System.out.println(json); isr.close(); is.close(); JSONArray ja = JSONArray.parseArray(json);