zoukankan      html  css  js  c++  java
  • Servlet学习五——流的分发

         在上一节中有提到,流的传输,可以考虑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);
    	}
    

      

    欢迎访问SuperMap技术问答社区http://qa.supermap.com/
  • 相关阅读:
    poj 3714 Raid(平面最近点对)
    hdu 4638 Group(离线+树状数组)
    UVa 10294(polya 翻转与旋转)
    hdu 4633 Who's Aunt Zhang(polya+逆元)
    Use of Function Arctan
    codeforces 299E Cube Problem
    UVa11806 Cheerleaders(容斥原理)
    UVa11538 A Chess Queen
    UVa11401
    周报(2017.3.19-3.16)
  • 原文地址:https://www.cnblogs.com/emily_fly/p/3486635.html
Copyright © 2011-2022 走看看