你的位置:首页 > 操作系统

[操作系统]从一个URL下载原始数据,基于byte字节,得到byte数组

 1 public static byte[] loadRawDataFromURL(String u) throws Exception { 2     URL url = new URL(u); 3     HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 4  5     InputStream is = conn.getInputStream(); 6     BufferedInputStream bis = new BufferedInputStream(is); 7  8     ByteArrayOutputStream baos = new ByteArrayOutputStream(); 9      //缓存2KB10     final int BUFFER_SIZE = 2*1024;11     final int EOF = -1;12 13     int c;14     byte[] buf = new byte[BUFFER_SIZE];15 16     while (true) {17       c = bis.read(buf);18       if (c == EOF)19         break;20 21       baos.write(buf, 0, c);22     }23 24     conn.disconnect();25     is.close();26 27     byte[] data = baos.toByteArray();28     baos.flush();29 30     return data;31   }