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

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

源代码1 项目: file-service   文件: ImageUtils.java
public static MultipartFile cutImage(MultipartFile file, Double rotate, Integer axisX, Integer axisY, Integer width, Integer height) throws java.io.IOException {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    if (rotate != null) {
        Thumbnails.of(file.getInputStream()).scale(1.0, 1.0).rotate(rotate).toOutputStream(outputStream);
    }
    if (axisX != null && axisY != null && width != null && height != null) {
        if (outputStream.size() > 0) {
            final InputStream rotateInputStream = new ByteArrayInputStream(outputStream.toByteArray());
            outputStream.reset();
            Thumbnails.of(rotateInputStream).scale(1.0, 1.0).sourceRegion(axisX, axisY, width, height).toOutputStream(outputStream);
        } else {
            Thumbnails.of(file.getInputStream()).scale(1.0, 1.0).sourceRegion(axisX, axisY, width, height).toOutputStream(outputStream);
        }
    }
    if (outputStream.size() > 0) {
        file = new MockMultipartFile(file.getName(), file.getOriginalFilename(),
                file.getContentType(), outputStream.toByteArray());
    }
    return file;
}
 
源代码2 项目: CrawlerForReader   文件: BitmapUtils.java
public static Bitmap compressBitmap(Bitmap image, int maxkb) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        int options = 90;

        image.compress(Bitmap.CompressFormat.JPEG, 90, baos);// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中

        while (baos.toByteArray().length / 1024 > maxkb) { // 循环判断如果压缩后图片是否大于(maxkb),大于继续压缩
            if (options > 10) {
                baos.reset();// 重置baos即清空baos
                options -= 10;// 每次都减少10
                image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%,把压缩后的数据存放到baos中
            } else {
                break;
            }
        }

        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中

        recycler(image);

        return BitmapFactory.decodeStream(isBm, null, null);
    }
 
源代码3 项目: NoVIP   文件: FileUtils.java
/**
 * 将图片保存到本地时进行压缩, 即将图片从Bitmap形式变为File形式时进行压缩,
 * 特点是: File形式的图片确实被压缩了, 但是当你重新读取压缩后的file为 Bitmap是,它占用的内存并没有改变
 *
 * @param bmp
 * @param file
 */
public static void compressBmpToFile(Bitmap bmp, File file) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int options = 80;// 个人喜欢从80开始,
    bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
    while (baos.toByteArray().length / 1024 > 100) {
        baos.reset();
        options -= 10;
        bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
    }
    try {
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(baos.toByteArray());
        fos.flush();
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
源代码4 项目: openjavacard-tools   文件: GPCrypto.java
/**
 * Special padding function for SCP01 encryption
 * <p/>
 * SCP01 uses its own padding scheme where the length
 * of the payload is prepended. If this block is now
 * a multiple of the blocksize then no further padding
 * is applied, otherwise pad80 is used.
 * <p/>
 * @param text
 * @param blocksize
 * @return
 */
public static byte[] pad80_scp01(byte[] text, int blocksize) {
    // SCP01 has optional padding, and it will
    // also prepend the length to the plaintext
    ByteArrayOutputStream plain = new ByteArrayOutputStream();
    int textLen = text.length;
    int totalSize = textLen + 1;
    plain.write(((byte) (textLen & 0xFF)));
    plain.write(text, 0, textLen);
    // check if padding required
    if ((totalSize % blocksize) != 0) {
        // perform padding (note this includes the length)
        byte[] padded = GPCrypto.pad80(plain.toByteArray(), blocksize);
        int paddedLen = padded.length;
        // recompose the plaintext
        plain.reset();
        plain.write(padded, 0, paddedLen);
    }
    return plain.toByteArray();
}
 
源代码5 项目: Getaviz   文件: GitCommit.java
private void addDiff(DiffImplementation returnable, RevCommit parent) throws IOException {
	RevWalk revWalk = new RevWalk(repository);
	parent = revWalk.parseCommit(parent.getId());
	revWalk.close();
	ByteArrayOutputStream put = new ByteArrayOutputStream(BUFFER_SIZE);
	DiffFormatter df = new DiffFormatter(put);
	df.setRepository(repository);
	df.setDiffComparator(RawTextComparator.DEFAULT);
	df.setDetectRenames(true);
	List<DiffEntry> diffs = df.scan(parent.getTree(), commit.getTree());
	for(DiffEntry e : diffs){
		df.format(e);
		String diffText = put.toString(DEFAULT_ENCODING); //TODO make encoding insertable
		returnable.addOperation(e.getOldPath(), new GitOperation(diffText, e.getOldPath(), e.getNewPath(), e.getChangeType()));
		put.reset();
	}
	df.close();
}
 
源代码6 项目: dts   文件: MetricsHttpServer.java
public void handle(HttpExchange t) throws IOException {
    String query = t.getRequestURI().getRawQuery();
    ByteArrayOutputStream response = this.response.get();
    response.reset();
    OutputStreamWriter osw = new OutputStreamWriter(response);
    TextFormat.write004(osw, registry.filteredMetricFamilySamples(parseQuery(query)));
    osw.flush();
    osw.close();
    response.flush();
    response.close();
    t.getResponseHeaders().set("Content-Type", TextFormat.CONTENT_TYPE_004);
    t.getResponseHeaders().set("Content-Length", String.valueOf(response.size()));
    if (shouldUseCompression(t)) {
        t.getResponseHeaders().set("Content-Encoding", "gzip");
        t.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0);
        final GZIPOutputStream os = new GZIPOutputStream(t.getResponseBody());
        response.writeTo(os);
        os.finish();
    } else {
        t.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.size());
        response.writeTo(t.getResponseBody());
    }
    t.close();
}
 
源代码7 项目: android_9.0.0_r45   文件: NetworkStatsRecorder.java
/**
 * Recover from {@link FileRotator} failure by dumping state to
 * {@link DropBoxManager} and deleting contents.
 */
private void recoverFromWtf() {
    if (DUMP_BEFORE_DELETE) {
        final ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            mRotator.dumpAll(os);
        } catch (IOException e) {
            // ignore partial contents
            os.reset();
        } finally {
            IoUtils.closeQuietly(os);
        }
        mDropBox.addData(TAG_NETSTATS_DUMP, os.toByteArray(), 0);
    }

    mRotator.deleteAll();
}
 
源代码8 项目: AndroidWallet   文件: ImageUtils.java
public static Bitmap compressImage(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
        int offset = 100;
        while (baos.toByteArray().length / 1024 > MAX_SIZE) {  //循环判断如果压缩后图片是否大于200kb,大于继续压缩

            baos.reset();//重置baos即清空baos
            image.compress(CompressFormat.JPEG, offset, baos);//这里压缩options%,把压缩后的数据存放到baos中
            offset -= 10;//每次都减少10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        //把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
        return bitmap;
    }
 
源代码9 项目: tysq-android   文件: BitmapUtil.java
/**
 * 压缩bitmp到目标大小(质量压缩)
 *
 * @param bitmap
 * @param needRecycle
 * @param maxSize
 * @return
 */
public static Bitmap compressBitmap(Bitmap bitmap, boolean needRecycle, long maxSize) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    int options = 100;
    while (baos.toByteArray().length > maxSize) {
        baos.reset();//重置baos即清空baos
        bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);
        options -= 10;//每次都减少10
    }
    ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
    Bitmap bm = BitmapFactory.decodeStream(isBm, null, null);
    if (needRecycle) {
        bitmap.recycle();
    }
    bitmap = bm;
    return bitmap;
}
 
源代码10 项目: styT   文件: FileUtil.java
/**
 * 获取压缩后图片的二进制数据
 * @param srcPath
 * @return
 */
public  byte[] getCompressedImage(String srcPath) {
    if (!new File(srcPath).exists()){
        return null;
    }

    BitmapFactory.Options newOpts = new BitmapFactory.Options();
    //开始读入图片,此时把options.inJustDecodeBounds 设回true了
    newOpts.inJustDecodeBounds = true;
    Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);//此时返回bm为空

    newOpts.inJustDecodeBounds = false;
    int w = newOpts.outWidth;
    int h = newOpts.outHeight;
    float hh = 800f;//这里设置高度为800f
    float ww = 480f;//这里设置宽度为480f
    //缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
    int be = 1;//be=1表示不缩放
    if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
        be = (int) (newOpts.outWidth / ww);
    } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
        be = (int) (newOpts.outHeight / hh);
    }
    if (be <= 0) {
        be = 1;
    }
    newOpts.inSampleSize = be;//设置缩放比例
    //重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
    bitmap = BitmapFactory.decodeFile(srcPath, newOpts);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
    int options = 100;
    while (baos.toByteArray().length / 1024 > 300) {    //循环判断如果压缩后图片是否大于300kb,大于继续压缩
        baos.reset();//重置baos即清空baos
        options -= 15;//每次都减少15
        bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中
    }
    return baos.toByteArray();
}
 
源代码11 项目: 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();
}
 
源代码12 项目: dragonwell8_jdk   文件: 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();
}
 
源代码13 项目: localization_nifi   文件: TestPostHTTP.java
@Test
public void testSendAsFlowFile() throws Exception {
    setup(null);
    runner.setProperty(PostHTTP.URL, server.getUrl());
    runner.setProperty(PostHTTP.SEND_AS_FLOWFILE, "true");

    final Map<String, String> attrs = new HashMap<>();
    attrs.put("abc", "cba");

    runner.enqueue("Hello".getBytes(), attrs);
    attrs.put("abc", "abc");
    attrs.put("filename", "xyz.txt");
    runner.enqueue("World".getBytes(), attrs);

    runner.run(1);
    runner.assertAllFlowFilesTransferred(PostHTTP.REL_SUCCESS);

    final byte[] lastPost = servlet.getLastPost();
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final ByteArrayInputStream bais = new ByteArrayInputStream(lastPost);

    FlowFileUnpackagerV3 unpacker = new FlowFileUnpackagerV3();

    // unpack first flowfile received
    Map<String, String> receivedAttrs = unpacker.unpackageFlowFile(bais, baos);
    byte[] contentReceived = baos.toByteArray();
    assertEquals("Hello", new String(contentReceived));
    assertEquals("cba", receivedAttrs.get("abc"));

    assertTrue(unpacker.hasMoreData());

    baos.reset();
    receivedAttrs = unpacker.unpackageFlowFile(bais, baos);
    contentReceived = baos.toByteArray();

    assertEquals("World", new String(contentReceived));
    assertEquals("abc", receivedAttrs.get("abc"));
    assertEquals("xyz.txt", receivedAttrs.get("filename"));
    Assert.assertNull(receivedAttrs.get("Content-Length"));
}
 
源代码14 项目: openjdk-jdk8u   文件: SignerOrder.java
static void printSignerInfos(SignerInfo[] signerInfos) throws IOException {
    ByteArrayOutputStream strm = new ByteArrayOutputStream();
    for (int i = 0; i < signerInfos.length; i++) {
        signerInfos[i].derEncode(strm);
        System.out.println("SignerInfo[" + i + "], length: "
                + strm.toByteArray().length);
        System.out.println(hexDump.encode(strm.toByteArray()));
        System.out.println("\n");
        strm.reset();
    }
}
 
源代码15 项目: RecyclerViewAdapter   文件: BitmapUtils.java
public static File compressBmpToFile(Bitmap bitmap, File file, Handler handler,int what) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int quality = 80;
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);

        while (baos.toByteArray().length / 1024 > 100 && quality > 50) {

            // 循环判断如果压缩后图片是否大于200kb,大于继续压缩,

            baos.reset();
            quality -= 10;
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);

        }
        try {
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(baos.toByteArray());
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Message message=Message.obtain();
        message.what=what;
        message.obj=file;
        handler.sendMessage(message);
        return file;
    }
 
源代码16 项目: android_9.0.0_r45   文件: AlarmManagerService.java
private void logBatchesLocked(SimpleDateFormat sdf) {
    ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
    PrintWriter pw = new PrintWriter(bs);
    final long nowRTC = System.currentTimeMillis();
    final long nowELAPSED = SystemClock.elapsedRealtime();
    final int NZ = mAlarmBatches.size();
    for (int iz = 0; iz < NZ; iz++) {
        Batch bz = mAlarmBatches.get(iz);
        pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
        dumpAlarmList(pw, bz.alarms, "  ", nowELAPSED, nowRTC, sdf);
        pw.flush();
        Slog.v(TAG, bs.toString());
        bs.reset();
    }
}
 
源代码17 项目: JavaInterview   文件: MultiThreadReader.java
@Override
public void run() {
    try {
        MappedByteBuffer mapBuffer = rAccessFile.getChannel().map(MapMode.READ_ONLY,start, this.sliceSize);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        for(int offset=0;offset<sliceSize;offset+=bufferSize){
            int readLength;
            if(offset+bufferSize<=sliceSize){
                readLength = bufferSize;
            }else{
                readLength = (int) (sliceSize-offset);
            }
            mapBuffer.get(readBuff, 0, readLength);
            for(int i=0;i<readLength;i++){
                byte tmp = readBuff[i];
                if(tmp=='\n' || tmp=='\r'){
                    handle(bos.toByteArray());
                    bos.reset();
                }else{
                    bos.write(tmp);
                }
            }
        }
        if(bos.size()>0){
            handle(bos.toByteArray());
        }
        cyclicBarrier.await();//测试性能用
    }catch (Exception e) {
        e.printStackTrace();
    }
}
 
源代码18 项目: panama   文件: FrameWrapper.java
public List<byte[]> unwrapFrames(byte[] bytes) {
    List<byte[]> ret = new ArrayList<>();

    byte[] data = new byte[unwrapBuffer.size() + bytes.length];
    System.arraycopy(unwrapBuffer.toByteArray(), 0, data, 0, unwrapBuffer.size());
    System.arraycopy(bytes, 0, data, unwrapBuffer.size(), bytes.length);
    unwrapBuffer.reset();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    int pos = 0, limit = pos + 1 + frameLength, size = data.length;
    while (pos < size) {
        byte[] buffer;
        switch (data[pos]) {
            case 0:
                limit = Math.min(limit + 1 + frameLength + 1, size);
                buffer = Arrays.copyOfRange(data, pos, limit);
                if (buffer.length < 1 + reservedHeaderLength) {
                    unwrapBuffer.write(buffer, 0, buffer.length);
                    // frame-len was truncated
                    return ret;
                }
                int endFrameLength = KeyHelper.toBigEndianInteger(Arrays.copyOfRange(buffer, 1, 1 + reservedHeaderLength));
                if (buffer.length < 1 + reservedHeaderLength + endFrameLength) {
                    unwrapBuffer.write(buffer, 0, buffer.length);
                    // data was truncated
                    return ret;
                } else {
                    outputStream.write(buffer, 1 + reservedHeaderLength, endFrameLength);
                    ret.add(outputStream.toByteArray());
                    outputStream.reset();
                    pos += 1 + reservedHeaderLength + endFrameLength;
                    limit = pos + 1 + frameLength;
                }
                break;
            case 1:
                buffer = Arrays.copyOfRange(data, pos, limit);
                outputStream.write(buffer, 1, buffer.length - 1);
                pos += 1 + frameLength;
                limit = Math.min(limit + 1 + frameLength, data.length);
                break;
            default:
                throw new RuntimeException("unknown delimiter " + data[pos]);
        }
    }
    return ret;
}
 
源代码19 项目: openjdk-jdk8u   文件: CheckLogging.java
/**
 * Check serverCallLog output
 */
private static void checkServerCallLog() throws Exception {
    ByteArrayOutputStream serverCallLog = new ByteArrayOutputStream();
    RemoteServer.setLog(serverCallLog);
    Naming.list(LOCATION);
    verifyLog(serverCallLog, "list");

    serverCallLog.reset();
    RemoteServer.setLog(null);
    PrintStream callStream = RemoteServer.getLog();
    if (callStream != null) {
        TestLibrary.bomb("call stream not null after calling " +
                         "setLog(null)");
    } else {
        System.err.println("call stream should be null and it is");
    }
    Naming.list(LOCATION);

    if (usingOld) {
        if (serverCallLog.toString().indexOf("UnicastServerRef") >= 0) {
            TestLibrary.bomb("server call logging not turned off");
        }
    } else if (serverCallLog.toByteArray().length != 0) {
        TestLibrary.bomb("call log contains output but it " +
                         "should be empty");
    }

    serverCallLog.reset();
    RemoteServer.setLog(serverCallLog);
    try {
        // generates a notbound exception
        Naming.lookup(LOCATION + "notthere");
    } catch (Exception e) {
    }
    verifyLog(serverCallLog, "exception");

    serverCallLog.reset();
    RemoteServer.setLog(serverCallLog);
    callStream = RemoteServer.getLog();
    callStream.println("bingo, this is a getLog test");
    verifyLog(serverCallLog, "bingo");
}
 
源代码20 项目: bcm-android   文件: ParseByteCacheTest.java
public void testTransaction(NetworkParameters params, byte[] txBytes, boolean isChild, boolean retain) throws Exception {

        // reference serializer to produce comparison serialization output after changes to
        // message structure.
        MessageSerializer bsRef = params.getSerializer(false);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        BitcoinSerializer bs = params.getSerializer(retain);
        Transaction t1;
        Transaction tRef;
        t1 = (Transaction) bs.deserialize(ByteBuffer.wrap(txBytes));
        tRef = (Transaction) bsRef.deserialize(ByteBuffer.wrap(txBytes));

        // verify our reference BitcoinSerializer produces matching byte array.
        bos.reset();
        bsRef.serialize(tRef, bos);
        assertTrue(Arrays.equals(bos.toByteArray(), txBytes));

        // check and retain status survive both before and after a serialization
        assertEquals(retain, t1.isCached());

        serDeser(bs, t1, txBytes, null, null);

        assertEquals(retain, t1.isCached());

        // compare to ref tx
        bos.reset();
        bsRef.serialize(tRef, bos);
        serDeser(bs, t1, bos.toByteArray(), null, null);

        // retrieve a value from a child
        t1.getInputs();
        if (t1.getInputs().size() > 0) {
            TransactionInput tin = t1.getInputs().get(0);
            assertEquals(retain, tin.isCached());

            // does it still match ref tx?
            serDeser(bs, t1, bos.toByteArray(), null, null);
        }

        // refresh tx
        t1 = (Transaction) bs.deserialize(ByteBuffer.wrap(txBytes));
        tRef = (Transaction) bsRef.deserialize(ByteBuffer.wrap(txBytes));

        // add an input
        if (t1.getInputs().size() > 0) {

            t1.addInput(t1.getInputs().get(0));

            // replicate on reference tx
            tRef.addInput(tRef.getInputs().get(0));

            assertFalse(t1.isCached());

            bos.reset();
            bsRef.serialize(tRef, bos);
            byte[] source = bos.toByteArray();
            //confirm we still match the reference tx.
            serDeser(bs, t1, source, null, null);
        }
    }