在上一節中有提到,流的傳輸,能夠考慮Stream,但若是須要同時分發流和其它信息,,就須要再考慮其它方式了。html
在coding中,服務端查詢結果都是以gson進行傳輸,當須要傳輸一個語音而且同時須要傳輸語音的相關信息時,就拿InputStream犯難了。在網上有搜到牛人的足跡,本身也實現了,分享思路及代碼。java
1.分發流思路:InputStream——byte[]——stringsql
首先是InputStream轉爲byte[]oracle
//SQL中Image字段實現 InputStream r = rs.getBinaryStream(2); //以下是Oracle中Blob字段實現 // oracle.sql.BLOB blob = null; // blob = (oracle.sql.BLOB) rs.getBlob(2); // java.io.InputStream r = blob.getBinaryStream(1L); byte[] cbuf = new byte[1024]; Integer iRead = 0; iRead = r.read(cbuf, 0, 1024); while (iRead.compareTo(-1) != 0) { fw.write(cbuf, 0, iRead); iRead = r.read(cbuf, 0, 1024); } fw.flush(); fw.close(); FileInputStream testfile = new FileInputStream(testName); byte[] bytes = new byte[(int) new File(testName).length()];
其次是byte[]轉stringapp
public String bytesToHexString(byte[] src) { StringBuilder stringBuilder = new StringBuilder(""); if (src == null || src.length <= 0) { return null; } for (int i = 0; i < src.length; i++) { int v = src[i] & 0xFF; String hv = Integer.toHexString(v); if (hv.length() < 2) { stringBuilder.append(0); } stringBuilder.append(hv); } return stringBuilder.toString(); }
在byte[]轉string過程當中,0xFF很是重要,最初沒有使用到這個,發現結果始終不對,後來將byte[]打印出來一看,還有符號表示,再到網上去查,瞭解到須要使用0xFF。ui
2.string到流:string——byte[]——Filehtm
public void saveByteFile(String strByteDesc, String strName) throws IOException { if (strByteDesc == null || strByteDesc.equals("")) { return; } strByteDesc = strByteDesc.toUpperCase(); int length = strByteDesc.length() / 2; char[] hexChars = strByteDesc.toCharArray(); byte[] d = new byte[length]; for (int i = 0; i < length; i++) { int pos = i * 2; d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1])); } File file = new File(strName); java.io.FileOutputStream fw = new java.io.FileOutputStream(file); fw.write(d, 0, d.length); fw.flush(); fw.close(); }
private static byte charToByte(char c) { return (byte) "0123456789ABCDEF".indexOf(c); }