Java Code Examples for java.io.ByteArrayOutputStream.close()

The following are Jave code examples for showing how to use close() of the java.io.ByteArrayOutputStream class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: dpdirect   File: FileUtils.java   View Source Code Vote up 6 votes
/**
 * Reads the byte content of an <code>InputStream</code>.
 * 
 * @param inputStream the <code>InputStream</code> from which to read content.
 * 
 * @return the byte content of the <code>InputStream</code>.
 * 
 * @exception IOException if there is an error reading the <code>InputStream</code>.
 */
public static byte[] readInputStreamBytes(InputStream inputStream) throws IOException {
   ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
   try {
      byte[] buffer = new byte[4096];
      int bytesRead = inputStream.read(buffer);
      while (bytesRead != -1) {
         outputStream.write(buffer, 0, bytesRead);
         bytesRead = inputStream.read(buffer);
      }
      return outputStream.toByteArray();
   }
   finally {
      outputStream.close();
   }
}
 
Example 2
Project: openjdk-jdk10   File: ZipDecompressor.java   View Source Code Vote up 6 votes
static byte[] decompress(byte[] bytesIn, int offset) throws Exception {
    Inflater inflater = new Inflater();
    inflater.setInput(bytesIn, offset, bytesIn.length - offset);
    ByteArrayOutputStream stream = new ByteArrayOutputStream(bytesIn.length - offset);
    byte[] buffer = new byte[1024];

    while (!inflater.finished()) {
        int count = inflater.inflate(buffer);
        stream.write(buffer, 0, count);
    }

    stream.close();

    byte[] bytesOut = stream.toByteArray();
    inflater.end();

    return bytesOut;
}
 
Example 3
Project: Android-Crop-Receipt   File: Utils.java   View Source Code Vote up 6 votes
public static Mat loadResource(Context context, int resourceId, int flags) throws IOException
{
    InputStream is = context.getResources().openRawResource(resourceId);
    ByteArrayOutputStream os = new ByteArrayOutputStream(is.available());

    byte[] buffer = new byte[4096];
    int bytesRead;
    while ((bytesRead = is.read(buffer)) != -1) {
        os.write(buffer, 0, bytesRead);
    }
    is.close();

    Mat encoded = new Mat(1, os.size(), CvType.CV_8U);
    encoded.put(0, 0, os.toByteArray());
    os.close();

    Mat decoded = Highgui.imdecode(encoded, flags);
    encoded.release();

    return decoded;
}
 
Example 4
Project: IJPay   File: SDKUtil.java   View Source Code Vote up 6 votes
/**
 * 压缩.
 * 
 * @param inputByte
 *            需要解压缩的byte[]数组
 * @return 压缩后的数据
 * @throws IOException
 */
public static byte[] deflater(final byte[] inputByte) throws IOException {
	int compressedDataLength = 0;
	Deflater compresser = new Deflater();
	compresser.setInput(inputByte);
	compresser.finish();
	ByteArrayOutputStream o = new ByteArrayOutputStream(inputByte.length);
	byte[] result = new byte[1024];
	try {
		while (!compresser.finished()) {
			compressedDataLength = compresser.deflate(result);
			o.write(result, 0, compressedDataLength);
		}
	} finally {
		o.close();
	}
	compresser.end();
	return o.toByteArray();
}
 
Example 5
Project: IJPay   File: SDKUtil.java   View Source Code Vote up 6 votes
/**
 * 解压缩.
 * 
 * @param inputByte
 *            byte[]数组类型的数据
 * @return 解压缩后的数据
 * @throws IOException
 */
public static byte[] inflater(final byte[] inputByte) throws IOException {
	int compressedDataLength = 0;
	Inflater compresser = new Inflater(false);
	compresser.setInput(inputByte, 0, inputByte.length);
	ByteArrayOutputStream o = new ByteArrayOutputStream(inputByte.length);
	byte[] result = new byte[1024];
	try {
		while (!compresser.finished()) {
			compressedDataLength = compresser.inflate(result);
			if (compressedDataLength == 0) {
				break;
			}
			o.write(result, 0, compressedDataLength);
		}
	} catch (Exception ex) {
		System.err.println("Data format error!\n");
		ex.printStackTrace();
	} finally {
		o.close();
	}
	compresser.end();
	return o.toByteArray();
}
 
Example 6
Project: SpringBoot-Study   File: Base64.java   View Source Code Vote up 6 votes
/**
 * 解密
 *
 * @param s
 * @return
 */
public static byte[] decode(String s) {

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        decode(s, bos);
    } catch (IOException e) {
        throw new RuntimeException();
    }
    byte[] decodedBytes = bos.toByteArray();
    try {
        bos.close();
        bos = null;
    } catch (IOException ex) {
        System.err.println("Error while decoding BASE64: " + ex.toString());
    }
    return decodedBytes;
}
 
Example 7
Project: Cable-Android   File: BitmapUtil.java   View Source Code Vote up 6 votes
public static byte[] createFromNV21(@NonNull final byte[] data,
                                    final int width,
                                    final int height,
                                    int rotation,
                                    final Rect croppingRect,
                                    final boolean flipHorizontal)
    throws IOException
{
  byte[] rotated = rotateNV21(data, width, height, rotation, flipHorizontal);
  final int rotatedWidth  = rotation % 180 > 0 ? height : width;
  final int rotatedHeight = rotation % 180 > 0 ? width  : height;
  YuvImage previewImage = new YuvImage(rotated, ImageFormat.NV21,
                                       rotatedWidth, rotatedHeight, null);

  ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  previewImage.compressToJpeg(croppingRect, 80, outputStream);
  byte[] bytes = outputStream.toByteArray();
  outputStream.close();
  return bytes;
}
 
Example 8
Project: SelectName   File: FileOperate.java   View Source Code Vote up 6 votes
/**
 * 描述: 从SDCard读取文件</br>
 * 开发人员:chixin</br>
 * 创建时间:2015-4-17</br>
 *
 * @param fileName
 * @return
 * @throws Exception
 */
public String readFromAsset(String fileName) throws Exception {
    String path = "offLineData/" + fileName;

    // 创建文件输入流对象
    InputStream inStream = context.getResources().getAssets().open(path);
    // 构建将转换输出流对象
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    // 定义一个字节缓存数组
    byte[] buffer = new byte[4096];
    // 读取的数据长度
    int len = 0;
    // 循环读取内容
    while ((len = inStream.read(buffer)) != -1) {
        // 将读取的内容写入流当中
        outStream.write(buffer, 0, len);
    }
    // 将读取的数据转换为字节数组
    byte[] datas = outStream.toByteArray();
    // 关闭输入流和输出流对象
    outStream.close();
    inStream.close();
    return new String(datas);// 返回读取字符串
}
 
Example 9
Project: KTools   File: SecurityUtils.java   View Source Code Vote up 6 votes
public static String bmp2base64(Bitmap bitmap, Bitmap.CompressFormat compressFormat,int quality){
    if (bitmap == null){
        return "";
    }else {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        bitmap.compress(compressFormat,quality,outputStream);
        try {
            outputStream.flush();
            outputStream.close();
            byte[] bytes = outputStream.toByteArray();

            return Base64.encodeToString(bytes,Base64.DEFAULT);

        } catch (IOException e) {
            return "";
        }
    }
}
 
Example 10
Project: incubator-netbeans   File: JarFileSystem.java   View Source Code Vote up 5 votes
private InputStream getMemInputStream(JarFile jf, JarEntry je)
throws IOException {
    InputStream is = getInputStream4336753(jf, je);
    ByteArrayOutputStream os = new ByteArrayOutputStream(is.available());

    try {
        FileUtil.copy(is, os);
    } finally {
        os.close();
    }

    return new ByteArrayInputStream(os.toByteArray());
}
 
Example 11
Project: opencron   File: RSAUtils.java   View Source Code Vote up 5 votes
/**
 * <p>
 * 公钥解密
 * </p>
 *
 * @param encryptedData 已加密数据
 * @param publicKey     公钥(BASE64编码)
 * @return
 * @throws Exception
 */
public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey) throws Exception {
    byte[] keyBytes = DigestUtils.getdeBASE64inCodec(publicKey);
    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    Key publicK = keyFactory.generatePublic(x509KeySpec);
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.DECRYPT_MODE, publicK);
    int inputLen = encryptedData.length;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int offSet = 0;
    byte[] cache;
    int i = 0;
    // 对数据分段解密
    while (inputLen - offSet > 0) {
        if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
            cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
        } else {
            cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
        }
        out.write(cache, 0, cache.length);
        i++;
        offSet = i * MAX_DECRYPT_BLOCK;
    }
    byte[] decryptedData = out.toByteArray();
    out.close();
    return decryptedData;
}
 
Example 12
Project: Flora   File: SingleActivity.java   View Source Code Vote up 5 votes
private void testBytes() {
    try {
        final InputStream is = getResources().getAssets().open("test4.jpg");

        long fileSize = is.available();

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int len = -1;
        while ((len = is.read(buffer)) != -1) {
            os.write(buffer, 0, len);
        }
        os.close();
        is.close();
        byte[] bitmapBytes = os.toByteArray();

        Bitmap originBitmap = BitmapFactory.decodeByteArray(bitmapBytes, 0, bitmapBytes.length);

        setupSourceInfo(originBitmap, fileSize);

        Flora.with(TAG).load(bitmapBytes).compress(new Callback<String>() {
            @Override
            public void callback(String s) {
                File file = new File(s);
                setupResultInfo(s, file.length());
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 13
Project: prada   File: StreamTool.java   View Source Code Vote up 5 votes
public static byte[] readStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;
        while( (len=inStream.read(buffer)) != -1){
            outSteam.write(buffer, 0, len);
        }
        outSteam.close();
        inStream.close();
        return outSteam.toByteArray();
}
 
Example 14
Project: ctsms   File: FileServiceImpl.java   View Source Code Vote up 5 votes
@Override
protected FilePDFVO handleAggregatePDFFiles(AuthenticationVO auth, FileModule module, Long id, String logicalPath, Boolean active, PSFVO psf) throws Exception {
	checkFileModuleId(module, id);
	FileDao fileDao = this.getFileDao();
	Timestamp now = new Timestamp(System.currentTimeMillis());
	User user = CoreUtil.getUser();
	Collection files = fileDao.findFiles(module, id, logicalPath, active, null, CoreUtil.PDF_MIMETYPE_STRING, psf);
	PDFMerger merger = new PDFMerger(fileDao);
	merger.setFiles(files);
	fileDao.toFileOutVOCollection(files);
	FilePDFVO pdfVO = new FilePDFVO();
	pdfVO.setContentTimestamp(now);
	pdfVO.setRequestingUser(this.getUserDao().toUserOutVO(user));
	ByteArrayOutputStream stream = new ByteArrayOutputStream();
	try {
		merger.save(stream);
	} finally {
		stream.close();
	}
	byte[] documentData = stream.toByteArray();
	pdfVO.setContentType(CoreUtil.getPDFMimeType());
	pdfVO.setFiles(files);
	StringBuilder fileName = new StringBuilder(PDFMerger.AGGREGATED_PDF_FILES_FILENAME_PREFIX);
	fileName.append(module.getValue());
	fileName.append("_");
	fileName.append(id);
	fileName.append("_");
	fileName.append(CommonUtil.formatDate(now, CommonUtil.DIGITS_ONLY_DATETIME_PATTERN));
	fileName.append(".");
	fileName.append(CoreUtil.PDF_FILENAME_EXTENSION);
	pdfVO.setFileName(fileName.toString());
	pdfVO.setMd5(CommonUtil.getHex(MessageDigest.getInstance("MD5").digest(documentData)));
	pdfVO.setSize(documentData.length);
	addAggregatedPDFFilesExportedJournalEntry(module, id, pdfVO, now, user);
	pdfVO.setDocumentDatas(documentData);
	return pdfVO;
}
 
Example 15
Project: jaer   File: XYTypeFilter.java   View Source Code Vote up 5 votes
synchronized public void doSaveMultiSelection() {
    if (selectionList == null) {
        log.warning("no profile to save");
        return;
    }
    try {
        int xValue[] = new int[selectionList.size()];
        int yValue[] = new int[selectionList.size()];
        int widthValue[] = new int[selectionList.size()];
        int heightValue[] = new int[selectionList.size()];
        Iterator iterator = selectionList.iterator();
        int j = 0;
        while (iterator.hasNext()) {
            SelectionRectangle tmpRect = (SelectionRectangle) iterator.next();
            xValue[j] = tmpRect.x;
            yValue[j] = tmpRect.y;
            widthValue[j] = tmpRect.width;
            heightValue[j] = tmpRect.height;
            j++;
        }

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(xValue);
        oos.writeObject(yValue);
        oos.writeObject(widthValue);
        oos.writeObject(heightValue);
        prefs().putByteArray("XYTypeFilter.multiSelection", bos.toByteArray());
        oos.close();
        bos.close();
        log.info("multi selection saveed to preferences");
    } catch (Exception e) {
        log.warning("couldn't save profile: " + e);
    }

}
 
Example 16
Project: neoscada   File: UrlConnectionInput.java   View Source Code Vote up 5 votes
@Override
protected Data makeData () throws Exception
{
    final URLConnection connection = this.url.openConnection ();
    connection.connect ();

    final int len = connection.getContentLength ();

    final ByteArrayOutputStream bos = new ByteArrayOutputStream ( len > 0 ? len : 0 );

    final byte[] buffer = new byte[4096];
    try ( InputStream stream = connection.getInputStream () )
    {
        int rc;
        while ( ( rc = stream.read ( buffer ) ) > 0 )
        {
            bos.write ( buffer, 0, rc );
        }
        bos.close ();
    }

    final String encoding = connection.getContentEncoding ();
    final String type = connection.getContentType ();

    logger.debug ( "Content-Encoding: {}", encoding );
    logger.debug ( "Content-Type: {}", type );

    Charset charset = null;

    if ( this.charset != null )
    {
        charset = this.charset;
    }
    else if ( this.probeCharset )
    {
        charset = makeCharsetFromType ( type );
    }

    return new UrlConnectionData ( convert ( buffer, charset ), null );
}
 
Example 17
Project: powsybl-core   File: AbstractMatrixTest.java   View Source Code Vote up 5 votes
protected String print(Matrix matrix, List<String> rowNames, List<String> columnNames) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        matrix.print(new PrintStream(bos), rowNames, columnNames);
    } finally {
        bos.close();
    }
    return bos.toString(StandardCharsets.UTF_8.name());
}
 
Example 18
Project: https-github.com-apache-zookeeper   File: Leader.java   View Source Code Vote up 4 votes
/**
 * create a proposal and send it out to all the members
 *
 * @param request
 * @return the proposal that is queued to send to all the members
 */
public Proposal propose(Request request) throws XidRolloverException {
    /**
     * Address the rollover issue. All lower 32bits set indicate a new leader
     * election. Force a re-election instead. See ZOOKEEPER-1277
     */
    if ((request.zxid & 0xffffffffL) == 0xffffffffL) {
        String msg =
                "zxid lower 32 bits have rolled over, forcing re-election, and therefore new epoch start";
        shutdown(msg);
        throw new XidRolloverException(msg);
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    BinaryOutputArchive boa = BinaryOutputArchive.getArchive(baos);
    try {
        request.getHdr().serialize(boa, "hdr");
        if (request.getTxn() != null) {
            request.getTxn().serialize(boa, "txn");
        }
        baos.close();
    } catch (IOException e) {
        LOG.warn("This really should be impossible", e);
    }
    QuorumPacket pp = new QuorumPacket(Leader.PROPOSAL, request.zxid,
            baos.toByteArray(), null);

    Proposal p = new Proposal();
    p.packet = pp;
    p.request = request;                
    
    synchronized(this) {
       p.addQuorumVerifier(self.getQuorumVerifier());
               
       if (request.getHdr().getType() == OpCode.reconfig){
           self.setLastSeenQuorumVerifier(request.qv, true);                       
       }
       
       if (self.getQuorumVerifier().getVersion()<self.getLastSeenQuorumVerifier().getVersion()) {
           p.addQuorumVerifier(self.getLastSeenQuorumVerifier());
       }
               
        if (LOG.isDebugEnabled()) {
            LOG.debug("Proposing:: " + request);
        }

        lastProposed = p.packet.getZxid();
        outstandingProposals.put(lastProposed, p);
        sendPacket(pp);
    }
    return p;
}
 
Example 19
Project: FLAC-library-Java   File: FrameEncoder.java   View Source Code Vote up 4 votes
public static SizeEstimate<FrameEncoder> computeBest(int sampleOffset, long[][] samples, int sampleDepth, int sampleRate, SubframeEncoder.SearchOptions opt) {
	FrameEncoder enc = new FrameEncoder(sampleOffset, samples, sampleDepth, sampleRate);
	int numChannels = samples.length;
	@SuppressWarnings("unchecked")
	SizeEstimate<SubframeEncoder>[] encoderInfo = new SizeEstimate[numChannels];
	if (numChannels != 2) {
		enc.metadata.channelAssignment = numChannels - 1;
		for (int i = 0; i < encoderInfo.length; i++)
			encoderInfo[i] = SubframeEncoder.computeBest(samples[i], sampleDepth, opt);
	} else {  // Explore the 4 stereo encoding modes
		long[] left  = samples[0];
		long[] right = samples[1];
		long[] mid  = new long[samples[0].length];
		long[] side = new long[mid.length];
		for (int i = 0; i < mid.length; i++) {
			mid[i] = (left[i] + right[i]) >> 1;
			side[i] = left[i] - right[i];
		}
		SizeEstimate<SubframeEncoder> leftInfo  = SubframeEncoder.computeBest(left , sampleDepth, opt);
		SizeEstimate<SubframeEncoder> rightInfo = SubframeEncoder.computeBest(right, sampleDepth, opt);
		SizeEstimate<SubframeEncoder> midInfo   = SubframeEncoder.computeBest(mid  , sampleDepth, opt);
		SizeEstimate<SubframeEncoder> sideInfo  = SubframeEncoder.computeBest(side , sampleDepth + 1, opt);
		long mode1Size = leftInfo.sizeEstimate + rightInfo.sizeEstimate;
		long mode8Size = leftInfo.sizeEstimate + sideInfo.sizeEstimate;
		long mode9Size = rightInfo.sizeEstimate + sideInfo.sizeEstimate;
		long mode10Size = midInfo.sizeEstimate + sideInfo.sizeEstimate;
		long minimum = Math.min(Math.min(mode1Size, mode8Size), Math.min(mode9Size, mode10Size));
		if (mode1Size == minimum) {
			enc.metadata.channelAssignment = 1;
			encoderInfo[0] = leftInfo;
			encoderInfo[1] = rightInfo;
		} else if (mode8Size == minimum) {
			enc.metadata.channelAssignment = 8;
			encoderInfo[0] = leftInfo;
			encoderInfo[1] = sideInfo;
		} else if (mode9Size == minimum) {
			enc.metadata.channelAssignment = 9;
			encoderInfo[0] = sideInfo;
			encoderInfo[1] = rightInfo;
		} else if (mode10Size == minimum) {
			enc.metadata.channelAssignment = 10;
			encoderInfo[0] = midInfo;
			encoderInfo[1] = sideInfo;
		} else
			throw new AssertionError();
	}
	
	// Add up subframe sizes
	long size = 0;
	enc.subEncoders = new SubframeEncoder[encoderInfo.length];
	for (int i = 0; i < enc.subEncoders.length; i++) {
		size += encoderInfo[i].sizeEstimate;
		enc.subEncoders[i] = encoderInfo[i].encoder;
	}
	
	// Count length of header (always in whole bytes)
	try {
		ByteArrayOutputStream bout = new ByteArrayOutputStream();
		try (BitOutputStream bitout = new BitOutputStream(bout)) {
			enc.metadata.writeHeader(bitout);
		}
		bout.close();
		size += bout.toByteArray().length * 8;
	} catch (IOException e) {
		throw new AssertionError(e);
	}
	
	// Count padding and footer
	size = (size + 7) / 8;  // Round up to nearest byte
	size += 2;  // CRC-16
	return new SizeEstimate<>(size, enc);
}
 
Example 20
Project: Auto.js-ApkBuilder   File: StringBlock.java   View Source Code Vote up 4 votes
public ByteArrayOutputStream writeString(List<String> stringlist) throws IOException {
	ByteArrayOutputStream bOut = new ByteArrayOutputStream();
	LEDataOutputStream mStrings = new LEDataOutputStream(bOut);

	// 字符串数量
	int size = stringlist.size();

	// 每串字符串在文件中的偏移位置
	stringOffsets = new int[size];
	// 字符串的长度
	int len = 0;

	for (int i = 0; i < size; i++) {
		// 获取列表中的字符串
		String var = stringlist.get(i);
		// 获取字符串的长度
		int length = var.length();
		// 获取字符串的偏移
		stringOffsets[i] = len;
		// 将字符串写入流中
		writeString(var, mStrings);
		// 如果第index个字符串是UTF-16型
		if ((flags & UTF8_FLAG) == 0) {
			// 为什么要大于这个数,这是我分析出来的
			if (length > 0x00007fff) {
				// 字符串在文件中储存的长度偏移2
				len += 2;
			}
			// 字符串在文件中储存的长度偏移2
			len += 2;
			// 字符串在文件中储存的长度偏移该字符串占用的字节的长度
			len += var.getBytes("UTF-16LE").length;
			// 字符串在文件中储存的长度偏移2
			len += 2;
		} else { // 如果是UTF-8型
			if (length > 0x0000007f) {
				// 字符串在文件中储存的长度偏移1
				len += 1;
			}
			// 字符串在文件中储存的长度偏移1
			len += 1;
			// 获取字符串在内存中的字节
			byte[] bytes = var.getBytes("UTF8");
			// 获取该字符串占用字节的大小
			length = bytes.length;
			if (length > 0x0000007f) {
				// 字符串在文件中储存的长度偏移1
				len += 1;
			}
			// 字符串在文件中储存的长度偏移1
			len += 1;
			// 字符串在文件中储存的长度偏移该字符串占用的字节的长度
			len += length;
			// 字符串在文件中储存的长度偏移1
			len += 1;
		}
	}

	// 偏移 0
	/*
	 * while (mStrings.size()%4!=0) { mStrings.writeByte((byte)0); }
	 */
	int size_mod = mStrings.size() % 4;// m_strings_size%4
	// 写入一些0字节用来填充,以确保arsc文件的正确性
	for (int i = 0; i < 4 - size_mod; i++) {
		mStrings.writeByte((byte) 0);
	}
	bOut.close();
	return bOut;
}