JAVA根据下载地址获取文件的Base64
//获取网络文件转 base64 public String fileToBase64(String urlStr) { int byteread = 0; String total = null; byte[] totalbyte = new byte[0]; InputStream inStream = null; try { inStream = getStream(urlStr); byte[] buffer = new byte[1024]; while ((byteread = inStream.read(buffer)) != -1) { //拼接流,这样写是保证文件不会被篡改 totalbyte = byteMerger(totalbyte, buffer, byteread); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (null != inStream) inStream.close(); } catch (IOException e) { e.printStackTrace(); } } return Base64.encodeBase64String(totalbyte); } //合并数组 private byte[] byteMerger(byte[] totalArr, byte[] mergerArr, int mergerLen) { if (null == totalArr || null == mergerArr) return totalArr; if (mergerLen == 0 || mergerLen > mergerArr.length) { throw new RuntimeException("mergerLen : " + mergerArr + " ,mergerArrLen : " + mergerArr.length); } int len = totalArr.length; byte[] reArr = new byte[len + mergerLen]; System.arraycopy(totalArr, 0, reArr, 0, len); System.arraycopy(mergerArr, 0, reArr, len, mergerLen); return reArr; } //根据 url 获取输入流 private final InputStream getStream(String urlStr) throws IOException { URL url = new URL(urlStr); HttpURLConnection httpUrl = (HttpURLConnection) url.openConnection(); httpUrl.connect(); httpUrl.getInputStream(); InputStream in = httpUrl.getInputStream(); return in; }
当你看清人们的真相,于是你知道了,你可以忍受孤独