java.io.ByteArrayOutputStream#write ( )源码实例Demo

下面列出了java.io.ByteArrayOutputStream#write ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: Kettle   文件: CraftPlayer.java
public void sendSupportedChannels() {
    if (getHandle().connection == null) return;
    Set<String> listening = server.getMessenger().getIncomingChannels();

    if (!listening.isEmpty()) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();

        for (String channel : listening) {
            try {
                stream.write(channel.getBytes(StandardCharsets.UTF_8));
                stream.write((byte) 0);
            } catch (IOException ex) {
                Logger.getLogger(CraftPlayer.class.getName()).log(Level.SEVERE, "Could not send Plugin Channel REGISTER to " + getName(), ex);
            }
        }

        getHandle().connection.sendPacket(new SPacketCustomPayload("REGISTER", new PacketBuffer(Unpooled.wrappedBuffer(stream.toByteArray()))));
    }
}
 
源代码2 项目: Android-POS   文件: SmartPost.java
/**
 * 
 * @param cmd ��������������CMD��
 * @param code ACK/NAK����
 * @return
 */
public static byte[] InitMessage(byte cmd, String code) {
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	try {
		baos.write(PostDefine.START);
		baos.write(cmd);
		if (code != null) {
			baos.write(PostDefine.FS);
			baos.write(code.getBytes());
		}
		baos.write(PostDefine.END);
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return baos.toByteArray();
}
 
private static void decrypt(byte[] encryptedBytes, ByteArrayOutputStream baos, int index, int blockSize, ConnectorCryptoUtils.Decryptor decryptor) throws IOException, IllegalBlockSizeException, BadPaddingException {
   if (blockSize == 0) {
      baos.write(decryptor.doFinal(encryptedBytes, 0, encryptedBytes.length));
   } else {
      for(; index < encryptedBytes.length; index += blockSize) {
         if (index + blockSize >= encryptedBytes.length) {
            baos.write(decryptor.doFinal(encryptedBytes, index, blockSize));
         } else {
            byte[] blockResult = decryptor.update(encryptedBytes, index, blockSize);
            if (blockResult != null) {
               baos.write(blockResult);
            }
         }
      }
   }

}
 
@Override
public byte[] toBytes() {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        bos.write(0); // never any data
        bos.write(0); // never any data
        if(appletAID == null) {
            throw new IOException("Applet AID is mandatory");
        } else {
            bos.write(appletAID.getLength());
            bos.write(appletAID.getBytes());
        }
        bos.write(0); // never any data
        bos.write(0); // never any data
        bos.write(0); // never any data
    } catch (IOException e) {
        throw new Error("Error serializing INSTALL [for PERSONALIZE] request", e);
    }
    return bos.toByteArray();
}
 
源代码5 项目: bcm-android   文件: Script.java
/**
 * Creates a program that requires at least N of the given keys to sign, using OP_CHECKMULTISIG.
 */
public static byte[] createMultiSigOutputScript(int threshold, List<ECKey> pubkeys) {
    checkArgument(threshold > 0);
    checkArgument(threshold <= pubkeys.size());
    checkArgument(pubkeys.size() <= 16);  // That's the max we can represent with a single opcode.
    if (pubkeys.size() > 3) {
        log.warn("Creating a multi-signature output that is non-standard: {} pubkeys, should be <= 3", pubkeys.size());
    }
    try {
        ByteArrayOutputStream bits = new ByteArrayOutputStream();
        bits.write(encodeToOpN(threshold));
        for (ECKey key : pubkeys) {
            writeBytes(bits, key.getPubKey());
        }
        bits.write(encodeToOpN(pubkeys.size()));
        bits.write(OP_CHECKMULTISIG);
        return bits.toByteArray();
    } catch (IOException e) {
        throw new RuntimeException(e);  // Cannot happen.
    }
}
 
源代码6 项目: green_android   文件: Dump.java
public static byte[] hexToBin(String src) {
    ByteArrayOutputStream result = new ByteArrayOutputStream();
    int i = 0;
    while (i < src.length()) {
            char x = src.charAt(i);
            if (!((x >= '0' && x <= '9') || (x >= 'A' && x <= 'F') || (x >= 'a' && x <= 'f'))) {
                    i++;
                    continue;
            }
            try {
                    result.write(Integer.valueOf("" + src.charAt(i) + src.charAt(i + 1), 16));
                    i += 2;
            }
            catch (Exception e) {
                    return null;
            }
    }
    return result.toByteArray();
}
 
private byte[] generateTimestampDigest(Element baseElement, String c14nMethodValue) {
   try {
      Node signatureValue = DomUtils.getMatchingChilds(baseElement, "http://www.w3.org/2000/09/xmldsig#", "SignatureValue").item(0);
      Transform transform = new Transform(signatureValue.getOwnerDocument(), c14nMethodValue);
      XMLSignatureInput refData = transform.performTransform(new XMLSignatureInput(signatureValue));
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      if (refData.isByteArray()) {
         baos.write(refData.getBytes());
      } else if (refData.isOctetStream()) {
         baos.write(ConnectorIOUtils.getBytes(refData.getOctetStream()));
      }

      return baos.toByteArray();
   } catch (Exception var7) {
      throw new IllegalArgumentException("Unable to calculateDigest", var7);
   }
}
 
源代码8 项目: dragonwell8_jdk   文件: WDataTransferer.java
@Override
protected ByteArrayOutputStream convertFileListToBytes(ArrayList<String> fileList)
        throws IOException
{
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    if(fileList.isEmpty()) {
        //store empty unicode string (null terminator)
        bos.write(UNICODE_NULL_TERMINATOR);
    } else {
        for (int i = 0; i < fileList.size(); i++) {
            byte[] bytes = fileList.get(i).getBytes(getDefaultUnicodeEncoding());
            //store unicode string with null terminator
            bos.write(bytes, 0, bytes.length);
            bos.write(UNICODE_NULL_TERMINATOR);
        }
    }

    // According to MSDN the byte array have to be double NULL-terminated.
    // The array contains Unicode characters, so each NULL-terminator is
    // a pair of bytes

    bos.write(UNICODE_NULL_TERMINATOR);
    return bos;
}
 
源代码9 项目: QNotified   文件: PubChemStealer.java
@NonUiThread
public static Molecule getMoleculeByCid(long cid) throws IOException, MdlMolParser.BadMolFormatException {
    HttpURLConnection conn = (HttpURLConnection) new URL(FAKE_PUB_CHEM_SITE + "/rest/pug/compound/CID/" + cid + "/record/SDF/?record_type=2d&response_type=display").openConnection();
    conn.setRequestMethod("GET");
    conn.setConnectTimeout(10000);
    conn.setReadTimeout(10000);
    if (conn.getResponseCode() != 200) {
        conn.disconnect();
        throw new IOException("Bad ResponseCode: " + conn.getResponseCode());
    }
    InputStream in = conn.getInputStream();
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int len;
    while ((len = in.read(buffer)) != -1) {
        outStream.write(buffer, 0, len);
    }
    in.close();
    conn.disconnect();
    String str = outStream.toString();
    return MdlMolParser.parseString(str);
}
 
源代码10 项目: TencentKona-8   文件: ValidateCertPath.java
private static byte[] getTotalBytes(InputStream is) throws IOException {
    byte[] buffer = new byte[8192];
    ByteArrayOutputStream baos = new ByteArrayOutputStream(2048);
    int n;
    baos.reset();
    while ((n = is.read(buffer, 0, buffer.length)) != -1) {
        baos.write(buffer, 0, n);
    }
    return baos.toByteArray();
}
 
源代码11 项目: jvm-sandbox-repeater   文件: HessianInput.java
/**
 * Reads a byte array
 *
 * <pre>
 * B b16 b8 data value
 * </pre>
 */
public byte []readBytes()
  throws IOException
{
  int tag = read();

  switch (tag) {
  case 'N':
    return null;

  case 'B':
  case 'b':
    _isLastChunk = tag == 'B';
    _chunkLength = (read() << 8) + read();

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    int data;
    while ((data = parseByte()) >= 0)
      bos.write(data);

    return bos.toByteArray();
    
  default:
    throw expect("bytes", tag);
  }
}
 
源代码12 项目: PacketProxy   文件: Utils.java
/**
 * EXEを実行する。MACの場合はmonoで実行する
 * @return 標準出力に表示されたデータ
 */
public static byte[] executeRuby(String... command) throws Exception
{

	Process p = Runtime.getRuntime().exec(addRubyPath(command));
	InputStream in = p.getInputStream();
	ByteArrayOutputStream bout = new ByteArrayOutputStream();
	byte [] buffer = new byte[4096];
	int len = 0;
	while ((len = in.read(buffer, 0, 4096)) > 0) {
		bout.write(buffer, 0, len);
	}
	return Base64.decodeBase64(bout.toByteArray());
}
 
源代码13 项目: bcm-android   文件: Util.java
public static String readFully(InputStream in) throws IOException {
  ByteArrayOutputStream bout = new ByteArrayOutputStream();
  byte[] buffer              = new byte[4096];
  int read;

  while ((read = in.read(buffer)) != -1) {
    bout.write(buffer, 0, read);
  }

  in.close();

  return new String(bout.toByteArray());
}
 
源代码14 项目: escpos-coffee   文件: EscPosTest.java
@Test
void setPrinterCharacterTableTest() throws Exception{
    ByteArrayOutputStream result = new ByteArrayOutputStream();
    EscPos escpos = new EscPos(result);

    escpos.setPrinterCharacterTable(10);
    escpos.close();
    ByteArrayOutputStream expected = new ByteArrayOutputStream();
    expected.write(ESC);
    expected.write('t');
    expected.write(10);

    assertArrayEquals(expected.toByteArray(), result.toByteArray());

}
 
源代码15 项目: java-n-IDE-for-Android   文件: ZipSigner.java
/**
 * Fetch the content from the given stream and return it as a byte array.
 */
public byte[] readContentAsBytes(InputStream input) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    byte[] buffer = new byte[2048];

    int numRead = input.read(buffer);
    while (numRead != -1) {
        baos.write(buffer, 0, numRead);
        numRead = input.read(buffer);
    }

    byte[] bytes = baos.toByteArray();
    return bytes;
}
 
源代码16 项目: quarkus   文件: OpenApiHandler.java
@Override
public void handle(RoutingContext event) {
    if (event.request().method().equals(HttpMethod.OPTIONS)) {
        addCorsResponseHeaders(event.response());
        event.response().headers().set("Allow", ALLOWED_METHODS);
    } else {
        HttpServerRequest req = event.request();
        HttpServerResponse resp = event.response();
        String accept = req.headers().get("Accept");

        List<String> formatParams = event.queryParam(QUERY_PARAM_FORMAT);
        String formatParam = formatParams.isEmpty() ? null : formatParams.get(0);

        // Default content type is YAML
        Format format = Format.YAML;

        // Check Accept, then query parameter "format" for JSON; else use YAML.
        if ((accept != null && accept.contains(Format.JSON.getMimeType())) ||
                ("JSON".equalsIgnoreCase(formatParam))) {
            format = Format.JSON;
        }

        addCorsResponseHeaders(resp);
        resp.headers().set("Content-Type", format.getMimeType() + ";charset=UTF-8");
        ClassLoader cl = classLoader == null ? Thread.currentThread().getContextClassLoader() : classLoader;
        try (InputStream in = cl.getResourceAsStream(BASE_NAME + format)) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int r;
            byte[] buf = new byte[1024];
            while ((r = in.read(buf)) > 0) {
                out.write(buf, 0, r);
            }
            resp.end(Buffer.buffer(out.toByteArray()));
        } catch (IOException e) {
            event.fail(e);
        }

    }
}
 
源代码17 项目: PacketProxy   文件: DataFrame.java
public byte[] getHttp() throws Exception {
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	baos.write("HTTP/2 200 OK\r\n".getBytes());
	baos.write(new String("X-PacketProxy-HTTP2-Stream-Id: " + streamId + "\r\n").getBytes());
	baos.write(new String("X-PacketProxy-HTTP2-Flags: " + flags + "\r\n").getBytes());
	baos.write("\r\n".getBytes());
	baos.write(payload);
	return baos.toByteArray();
}
 
源代码18 项目: DevUtils   文件: ResourceUtils.java
/**
 * 获取 Raw 资源文件数据并保存到本地
 * @param resId 资源 id
 * @param file  文件保存地址
 * @return {@code true} success, {@code false} fail
 */
public static boolean saveRawFormFile(@RawRes final int resId, final File file) {
    try {
        // 获取 raw 文件
        InputStream is = openRawResource(resId);
        // 存入 SDCard
        FileOutputStream fos = new FileOutputStream(file);
        // 设置数据缓冲
        byte[] buffer = new byte[1024];
        // 创建输入输出流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int len;
        while ((len = is.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
        // 保存数据
        byte[] bytes = baos.toByteArray();
        // 写入保存的文件
        fos.write(bytes);
        // 关闭流
        CloseUtils.closeIOQuietly(baos, is);
        fos.flush();
        CloseUtils.closeIOQuietly(fos);
        return true;
    } catch (Exception e) {
        LogPrintUtils.eTag(TAG, e, "saveRawFormFile");
    }
    return false;
}
 
源代码19 项目: bidder   文件: HttpPostGet.java
/**
 * Send an HTTP Post
 * @param targetURL
 *    String. The URL to transmit to.
 * @param data
 *            byte[]. The payload bytes.
 * @param connTimeout
 * 			  int. The connection timeout in ms
 * @param readTimeout
 * 			  int. The read timeout in ms.
 * @return byte[]. The contents of the POST return.
 * @throws Exception
 *             on network errors.
 */
public byte [] sendPost(String targetURL,  byte [] data, int connTimeout, int readTimeout) throws Exception {
	URLConnection connection = new URL(targetURL).openConnection();
	connection.setRequestProperty("Content-Type", "application/json");
	connection.setDoInput(true);
	connection.setDoOutput(true);
	connection.setConnectTimeout(connTimeout);
	connection.setReadTimeout(readTimeout);
	OutputStream output = connection.getOutputStream();
	
	try {
		output.write(data);
	} finally {
		try {
			output.close();
		} catch (IOException logOrIgnore) {
			logOrIgnore.printStackTrace();
		}
	}
	InputStream response = connection.getInputStream();
	
	http = (HttpURLConnection) connection;
	code = http.getResponseCode();
	
	String value = http.getHeaderField("Content-Encoding");
	
	if (value != null && value.equals("gzip")) {
		byte bytes [] = new byte[4096];
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		GZIPInputStream gis = new GZIPInputStream(http.getInputStream());
		while(true) {
			int n = gis.read(bytes);
			if (n < 0) break;
			baos.write(bytes,0,n);
		}
		return baos.toByteArray();
	}
	
		

	byte [] b = getContents(response);
	if (b.length == 0)
		return null;
	return b;
}
 
源代码20 项目: client-encryption-java   文件: EncodingUtils.java
@SuppressWarnings({"squid:S3776", "squid:ForLoopCounterChangedCheck"})
public static byte[] base64Decode(String value) {
    if (null == value) {
        throw new IllegalArgumentException("Can't base64 decode a null value!");
    }
    byte[] valueBytes = value.getBytes();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    for (int i = 0; i < valueBytes.length;) {
        int b;
        if (b64ints[valueBytes[i]] != -1) {
            b = (b64ints[valueBytes[i]] & 0xFF) << 18;
        }
        // skip unknown characters
        else {
            i++;
            continue;
        }

        int num = 0;
        if (i + 1 < valueBytes.length && b64ints[valueBytes[i + 1]] != -1) {
            b = b | ((b64ints[valueBytes[i + 1]] & 0xFF) << 12);
            num++;
        }
        if (i + 2 < valueBytes.length && b64ints[valueBytes[i + 2]] != -1) {
            b = b | ((b64ints[valueBytes[i + 2]] & 0xFF) << 6);
            num++;
        }
        if (i + 3 < valueBytes.length && b64ints[valueBytes[i + 3]] != -1) {
            b = b | (b64ints[valueBytes[i + 3]] & 0xFF);
            num++;
        }

        while (num > 0) {
            int c = (b & 0xFF0000) >> 16;
            outputStream.write((char)c);
            b <<= 8;
            num--;
        }
        i += 4;
    }
    return outputStream.toByteArray();
}