首页 技术 正文
技术 2022年11月15日
0 收藏 525 点赞 2,523 浏览 1698 个字

在上一节中有提到,流的传输,可以考虑Stream,但如果需要同时分发流和其它信息,,就需要再考虑其它方式了。

在coding中,服务端查询结果都是以gson进行传输,当需要传输一个语音并且同时需要传输语音的相关信息时,就拿InputStream犯难了。在网上有搜到牛人的足迹,自己也实现了,分享思路及代码。

1.分发流思路:InputStream——byte[]——string

首先是InputStream转为byte[]

//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[]转string

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。

2.string到流:string——byte[]——File

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);
}

  

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,077
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,552
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,401
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,176
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,813
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,896