下面列出了java.io.ByteArrayInputStream#read ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Reads an signed integer from {@code in}.
*/
public static int readSignedLeb128( ByteArrayInputStream in ) {
int result = 0;
int cur;
int count = 0;
int signBits = -1;
do {
cur = in.read( ) & 0xff;
result |= ( cur & 0x7f ) << ( count * 7 );
signBits <<= 7;
count++;
}
while ( ( ( cur & 0x80 ) == 0x80 ) && count < 5 );
if ( ( cur & 0x80 ) == 0x80 ) {
throw new DexException( "invalid LEB128 sequence" );
}
// Sign extend if appropriate
if ( ( ( signBits >> 1 ) & result ) != 0 ) {
result |= signBits;
}
return result;
}
/**
* Signed Little-endian Base-128
*/
protected long sleb128( ByteArrayInputStream byteStream, TaskMonitor monitor ) throws Exception {
long result = 0;
int bit = 0;
while ( !monitor.isCancelled() ) {
int value = byteStream.read();
if ( value == -1 ) {
break;
}
byte nextByte = (byte) value;
result |= ( ( nextByte & 0x7f ) << bit );
bit += 7;
if ( ( nextByte & 0x80 ) == 0 ) {
break;
}
}
return result;
}
@Override
public RocksEntry filterGet(byte[] valueFromRocks) {
if (isRawValue(valueFromRocks)) {
if (valueFromRocks == null) {
return null;
}
return new RocksEntry(null, valueFromRocks);
}
try {
// Slice off the prefix byte and start parsing where the metadata block is.
final ByteArrayInputStream bais = new ByteArrayInputStream(valueFromRocks, 1, valueFromRocks.length);
final Rocks.Meta meta = parseMetaAfterPrefix(bais);
// We know this is not a blob because we are using the inline blob manager. Assume the value
// is the rest of the byte array.
final byte[] result = new byte[bais.available()];
bais.read(result);
return new RocksEntry(meta, result);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* 解密
*
* @param data
* @param privateKey
* @param keySize
* @return
* @throws Exception
*/
public static byte[] decrypt(byte[] data, PrivateKey privateKey, int keySize)
throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING", "BC");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
int blockSize = keySize >> 3;
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buf = new byte[blockSize];
int len = 0;
while ((len = byteArrayInputStream.read(buf)) > 0) {
byteArrayOutputStream.write(cipher.doFinal(buf, 0, len));
}
return byteArrayOutputStream.toByteArray();
}
protected InputStream trimCRLFPrefix(byte[] data) {
ByteArrayInputStream bIn = new ByteArrayInputStream(data);
int scanPos = 0;
int len = data.length;
while (scanPos < (len - 1)) {
if (new String(data, scanPos, 2).equals("\r\n")) {
bIn.read();
bIn.read();
scanPos += 2;
} else {
return bIn;
}
}
return bIn;
}
/**
* Returns String value.
*/
public String getStringValue() {
//assumes only 1 attribute value. Will get the first value
// if > 1.
String strVal = null;
byte[] bufArray = (byte[])myValue;
if (bufArray != null) {
ByteArrayInputStream bufStream =
new ByteArrayInputStream(bufArray);
int valLength = bufStream.read();
byte[] strBytes = new byte[valLength];
bufStream.read(strBytes, 0, valLength);
try {
strVal = new String(strBytes, "UTF-8");
} catch (java.io.UnsupportedEncodingException uee) {
}
}
return strVal;
}
public static byte[] Decode(byte[] bytes, Ecdsa algorithm)
{
int coordLength = algorithm.getCoordLength();
ByteArrayInputStream asn1DerSignature = new ByteArrayInputStream(bytes);
// verify byte 0 is 0x30
if (asn1DerSignature.read() != 0x30)
{
throw new IllegalArgumentException("Invalid signature.");
}
int objLen = readFieldLength(asn1DerSignature);
// verify the object lenth is equal to the remaining length of the _asn1DerSignature
if (objLen != asn1DerSignature.available())
{
throw new IllegalArgumentException(String.format("Invalid signature; invalid field len %d", objLen));
}
byte[] rawSignature = new byte[coordLength * 2];
// decode the r feild to the first half of _rawSignature
decodeIntField(asn1DerSignature, rawSignature, 0, coordLength);
// decode the s feild to the second half of _rawSignature
decodeIntField(asn1DerSignature, rawSignature, rawSignature.length / 2, coordLength);
return rawSignature;
}
public static String toString(ByteArrayInputStream is) {
int size = is.available();
char[] theChars = new char[size];
byte[] bytes = new byte[size];
is.read(bytes, 0, size);
for (int i = 0; i < size;)
theChars[i] = (char)(bytes[i++]&0xff);
return new String(theChars);
}
public BitcoinInput(ByteArrayInputStream data) throws BTChipException {
try {
prevOut = new byte[36];
data.read(prevOut);
long scriptSize = VarintUtils.read(data);
script = new byte[(int)scriptSize];
data.read(script);
sequence = new byte[4];
data.read(sequence);
}
catch(Exception e) {
throw new BTChipException("Invalid encoding", e);
}
}
public static boolean validateVar(ByteArrayInputStream input) {
byte[] raw = new byte[input.available()];
input.mark(input.available());
input.read(raw, 0, input.available());
boolean ret = validateVar(raw);
input.reset();
return ret;
}
@Override
public long writeToFileAtURL(LocalFilesystemURL inputURL, String data,
int offset, boolean isBinary) throws IOException, NoModificationAllowedException {
boolean append = false;
if (offset > 0) {
this.truncateFileAtURL(inputURL, offset);
append = true;
}
byte[] rawData;
if (isBinary) {
rawData = Base64.decode(data, Base64.DEFAULT);
} else {
rawData = data.getBytes();
}
ByteArrayInputStream in = new ByteArrayInputStream(rawData);
try
{
byte buff[] = new byte[rawData.length];
FileOutputStream out = new FileOutputStream(this.filesystemPathForURL(inputURL), append);
try {
in.read(buff, 0, buff.length);
out.write(buff, 0, rawData.length);
out.flush();
} finally {
// Always close the output
out.close();
}
broadcastNewFile(inputURL);
}
catch (NullPointerException e)
{
// This is a bug in the Android implementation of the Java Stack
NoModificationAllowedException realException = new NoModificationAllowedException(inputURL.toString());
throw realException;
}
return rawData.length;
}
private void formatHex(String original, int length, String separator) throws IOException {
ByteArrayInputStream bis = new ByteArrayInputStream(original.getBytes());
byte[] buffer = new byte[length];
String result = "";
while (bis.read(buffer) > 0) {
for (byte b : buffer) {
result += (char) b;
}
Arrays.fill(buffer, (byte) 0);
result += separator;
}
hex = StringUtils.left(result, result.length() - 1);
}
public static int decodeBit32(ByteArrayInputStream input) throws Exception {
int bit32 = 0;
for (int idx = 0; idx < 4; idx++) {
int nextB = input.read();
bit32 = bit32 | (nextB << (8*idx));
}
return bit32;
}
@Override
public ServletInputStream getInputStream() throws IOException
{
final ByteArrayInputStream bais = new ByteArrayInputStream(body);
return new ServletInputStream()
{
@Override
public int read() throws IOException
{
return bais.read();
}
@Override
public boolean isFinished()
{
return false;
}
@Override
public boolean isReady()
{
return false;
}
@Override
public void setReadListener(ReadListener readListener)
{
}
};
}
@Override
public ServletInputStream getInputStream() throws IOException {
//非json类型,直接返回
if(!MediaType.APPLICATION_JSON_VALUE.equalsIgnoreCase(super.getHeader(HttpHeaders.CONTENT_TYPE))){
return super.getInputStream();
}
//为空,直接返回
String json = IOUtils.toString(super.getInputStream(), "utf-8");
if (StringUtils.isBlank(json)) {
return super.getInputStream();
}
//xss过滤
json = xssEncode(json);
final ByteArrayInputStream bis = new ByteArrayInputStream(json.getBytes("utf-8"));
return new ServletInputStream() {
@Override
public boolean isFinished() {
return true;
}
@Override
public boolean isReady() {
return true;
}
@Override
public void setReadListener(ReadListener readListener) {
}
@Override
public int read() throws IOException {
return bis.read();
}
};
}
private String toString(ByteArrayInputStream bais, String encoding) throws UnsupportedEncodingException {
int n = 0;
final byte[] bb = new byte[bais.available()];
while ((n = bais.read(bb, n, bb.length - n)) >= 0); // NOPMD ignore empty while block
bais.reset();
return new String(bb, encoding);
}
/**
* <p>To run a script, first we parse it which breaks it up into chunks representing pushes of data or logical
* opcodes. Then we can run the parsed chunks.</p>
*
* <p>The reason for this split, instead of just interpreting directly, is to make it easier
* to reach into a programs structure and pull out bits of data without having to run it.
* This is necessary to render the to/from addresses of transactions in a user interface.
* Bitcoin Core does something similar.</p>
*/
private void parse(byte[] program) throws ScriptException {
chunks = new ArrayList<>(5); // Common size.
ByteArrayInputStream bis = new ByteArrayInputStream(program);
int initialSize = bis.available();
while (bis.available() > 0) {
int startLocationInProgram = initialSize - bis.available();
int opcode = bis.read();
long dataToRead = -1;
if (opcode >= 0 && opcode < OP_PUSHDATA1) {
// Read some bytes of data, where how many is the opcode value itself.
dataToRead = opcode;
} else if (opcode == OP_PUSHDATA1) {
if (bis.available() < 1) throw new ScriptException("Unexpected end of script");
dataToRead = bis.read();
} else if (opcode == OP_PUSHDATA2) {
// Read a short, then read that many bytes of data.
if (bis.available() < 2) throw new ScriptException("Unexpected end of script");
dataToRead = bis.read() | (bis.read() << 8);
} else if (opcode == OP_PUSHDATA4) {
// Read a uint32, then read that many bytes of data.
// Though this is allowed, because its value cannot be > 520, it should never actually be used
if (bis.available() < 4) throw new ScriptException("Unexpected end of script");
dataToRead = ((long)bis.read()) | (((long)bis.read()) << 8) | (((long)bis.read()) << 16) | (((long)bis.read()) << 24);
}
ScriptChunk chunk;
if (dataToRead == -1) {
chunk = new ScriptChunk(opcode, null, startLocationInProgram);
} else {
if (dataToRead > bis.available())
throw new ScriptException("Push of data element that is larger than remaining data");
byte[] data = new byte[(int)dataToRead];
checkState(dataToRead == 0 || bis.read(data, 0, (int)dataToRead) == dataToRead);
chunk = new ScriptChunk(opcode, data, startLocationInProgram);
}
// Save some memory by eliminating redundant copies of the same chunk objects.
for (ScriptChunk c : STANDARD_TRANSACTION_SCRIPT_CHUNKS) {
if (c.equals(chunk)) chunk = c;
}
chunks.add(chunk);
}
}
@Override
public Boolean readObject(@NotNull final ByteArrayInputStream stream) {
return stream.read() != 0;
}
@Override
public InputStream read(FlowFile flowFile) {
if (flowFile == null) {
throw new IllegalArgumentException("FlowFile cannot be null");
}
final MockFlowFile mock = validateState(flowFile);
final ByteArrayInputStream bais = new ByteArrayInputStream(mock.getData());
incrementReadCount(flowFile);
final InputStream errorHandlingStream = new InputStream() {
@Override
public int read() throws IOException {
return bais.read();
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
return bais.read(b, off, len);
}
@Override
public void close() throws IOException {
decrementReadCount(flowFile);
openInputStreams.remove(mock);
bais.close();
}
@Override
public void mark(final int readlimit) {
bais.mark(readlimit);
}
@Override
public void reset() {
bais.reset();
}
@Override
public int available() throws IOException {
return bais.available();
}
@Override
public String toString() {
return "ErrorHandlingInputStream[flowFile=" + mock + "]";
}
};
openInputStreams.put(mock, errorHandlingStream);
return errorHandlingStream;
}
@Override
public long writeToFileAtURL(LocalFilesystemURL inputURL, String data,
int offset, boolean isBinary) throws IOException, NoModificationAllowedException {
boolean append = false;
if (offset > 0) {
this.truncateFileAtURL(inputURL, offset);
append = true;
}
byte[] rawData;
if (isBinary) {
rawData = Base64.decode(data, Base64.DEFAULT);
} else {
rawData = data.getBytes();
}
ByteArrayInputStream in = new ByteArrayInputStream(rawData);
try
{
byte buff[] = new byte[rawData.length];
String absolutePath = filesystemPathForURL(inputURL);
FileOutputStream out = new FileOutputStream(absolutePath, append);
try {
in.read(buff, 0, buff.length);
out.write(buff, 0, rawData.length);
out.flush();
} finally {
// Always close the output
out.close();
}
if (isPublicDirectory(absolutePath)) {
broadcastNewFile(Uri.fromFile(new File(absolutePath)));
}
}
catch (NullPointerException e)
{
// This is a bug in the Android implementation of the Java Stack
NoModificationAllowedException realException = new NoModificationAllowedException(inputURL.toString());
throw realException;
}
return rawData.length;
}