List of usage examples for java.io ByteArrayOutputStream close
public void close() throws IOException
From source file:com.runwaysdk.controller.ErrorUtility.java
private static String compress(String message) { try {//from ww w . j av a 2s .c om ByteArrayOutputStream bos = new ByteArrayOutputStream(); BufferedOutputStream bufos = new BufferedOutputStream(new GZIPOutputStream(bos)); bufos.write(message.getBytes("UTF-8")); bufos.close(); bos.close(); byte[] bytes = bos.toByteArray(); return Base64.encodeToString(bytes, false); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:edu.stanford.junction.addon.JSONObjWrapper.java
private static String compressString(String str) { byte[] input; try {//w ww .j a v a 2 s .c o m input = str.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { input = str.getBytes(); } // Create the compressor with highest level of compression Deflater compressor = new Deflater(); compressor.setLevel(Deflater.BEST_COMPRESSION); // Give the compressor the data to compress compressor.setInput(input); compressor.finish(); // Create an expandable byte array to hold the compressed data. // You cannot use an array that's the same size as the orginal because // there is no guarantee that the compressed data will be smaller than // the uncompressed data. ByteArrayOutputStream bos = new ByteArrayOutputStream(input.length); // Compress the data byte[] buf = new byte[1024]; while (!compressor.finished()) { int count = compressor.deflate(buf); bos.write(buf, 0, count); } try { bos.close(); } catch (IOException e) { } // Get the compressed data byte[] compressedData = bos.toByteArray(); return Base64.encodeBytes(compressedData); }
From source file:com.camel.trainreserve.TicketReserver.java
private static void getCaptchaImg() { String url = "https://kyfw.12306.cn/otn/passcodeNew/getPassCodeNew?module=passenger&rand=randp&0.20558934959469144"; ByteArrayOutputStream outStream = JDKHttpsClient.doGetImg(url, cookieStr); if (outStream.size() > 0) { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); File imageFile = new File("G://12306OCR-2//" + (new Date()).getTime() + ".png"); try {/*from w ww. j a v a2 s.com*/ FileOutputStream fos = new FileOutputStream(imageFile); byte[] bytes = outStream.toByteArray(); fos.write(bytes); fos.flush(); fos.close(); outStream.close(); } catch (IOException e) { e.printStackTrace(); } } else { System.out.println(Thread.currentThread().getName() + " return empty"); } }
From source file:org.dataone.proto.trove.mn.http.client.DataHttpClientHandler.java
public static synchronized String executePost(HttpClient httpclient, HttpPost httpPost) throws ServiceFailure, NotFound, InvalidToken, NotAuthorized, IdentifierNotUnique, UnsupportedType, InsufficientResources, InvalidSystemMetadata, NotImplemented, InvalidCredentials, InvalidRequest, AuthenticationTimeout, UnsupportedMetadataType, HttpException { String response = null;//from w ww . j av a 2s .co m try { HttpResponse httpResponse = httpclient.execute(httpPost); if (httpResponse.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) { HttpEntity resEntity = httpResponse.getEntity(); if (resEntity != null) { logger.debug("Response content length: " + resEntity.getContentLength()); logger.debug("Chunked?: " + resEntity.isChunked()); BufferedInputStream in = new BufferedInputStream(resEntity.getContent()); ByteArrayOutputStream resOutputStream = new ByteArrayOutputStream(); byte[] buff = new byte[32 * 1024]; int len; while ((len = in.read(buff)) > 0) { resOutputStream.write(buff, 0, len); } response = new String(resOutputStream.toByteArray()); logger.debug(response); resOutputStream.close(); in.close(); } } else { HttpExceptionHandler.deserializeAndThrowException(httpResponse); } } catch (IOException ex) { throw new ServiceFailure("1002", ex.getMessage()); } return response; }
From source file:com.example.facebook_photo.Utility.java
public static byte[] scaleImage(Context context, Uri photoUri) throws IOException { InputStream is = context.getContentResolver().openInputStream(photoUri); BitmapFactory.Options dbo = new BitmapFactory.Options(); dbo.inJustDecodeBounds = true;/*from w w w . j a v a 2 s . c o m*/ BitmapFactory.decodeStream(is, null, dbo); is.close(); int rotatedWidth, rotatedHeight; int orientation = getOrientation(context, photoUri); if (orientation == 90 || orientation == 270) { rotatedWidth = dbo.outHeight; rotatedHeight = dbo.outWidth; } else { rotatedWidth = dbo.outWidth; rotatedHeight = dbo.outHeight; } Bitmap srcBitmap; is = context.getContentResolver().openInputStream(photoUri); if (rotatedWidth > MAX_IMAGE_DIMENSION || rotatedHeight > MAX_IMAGE_DIMENSION) { float widthRatio = ((float) rotatedWidth) / ((float) MAX_IMAGE_DIMENSION); float heightRatio = ((float) rotatedHeight) / ((float) MAX_IMAGE_DIMENSION); float maxRatio = Math.max(widthRatio, heightRatio); // Create the bitmap from file BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = (int) maxRatio; srcBitmap = BitmapFactory.decodeStream(is, null, options); } else { srcBitmap = BitmapFactory.decodeStream(is); } is.close(); /* * if the orientation is not 0 (or -1, which means we don't know), we * have to do a rotation. */ if (orientation > 0) { Matrix matrix = new Matrix(); matrix.postRotate(orientation); srcBitmap = Bitmap.createBitmap(srcBitmap, 0, 0, srcBitmap.getWidth(), srcBitmap.getHeight(), matrix, true); } String type = context.getContentResolver().getType(photoUri); ByteArrayOutputStream baos = new ByteArrayOutputStream(); if (type.equals("image/png")) { srcBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); } else if (type.equals("image/jpg") || type.equals("image/jpeg")) { srcBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); } byte[] bMapArray = baos.toByteArray(); baos.close(); return bMapArray; }
From source file:org.epics.archiverappliance.utils.ui.GetUrlContent.java
/** * Small utility method for getting the content of an URL as a string * Returns null in case of an exception. * @param urlStr URL/*from w w w .j a v a 2 s . c om*/ * @return URL content */ public static String getURLContent(String urlStr) { try { logger.debug("Getting the contents of " + urlStr + " as a string."); try (InputStream is = getURLContentAsStream(urlStr)) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(is, bos); bos.close(); return new String(bos.toByteArray(), "UTF-8"); } } catch (IOException ex) { logger.error("Exception getting contents of internal URL " + urlStr, ex); } return null; }
From source file:com.ckfinder.connector.utils.ImageUtils.java
/** * writes unchanged file to disk./*from ww w .j a v a 2 s . c o m*/ * * @param stream - stream to read the file from * * @param destFile - file to write to * * @throws IOException when error occurs. */ private static void writeUntouchedImage(final InputStream stream, final File destFile) throws IOException { ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream(); byte[] buffer = new byte[MAX_BUFF_SIZE]; int readNum = -1; while ((readNum = stream.read(buffer)) != -1) { byteArrayOS.write(buffer, 0, readNum); } byte[] bytes = byteArrayOS.toByteArray(); byteArrayOS.close(); FileOutputStream fileOS = new FileOutputStream(destFile); fileOS.write(bytes); fileOS.flush(); fileOS.close(); }
From source file:com.example.ridemedriver.SignupStepTwoActivity.java
public static byte[] readStream(InputStream inStream) throws Exception { byte[] buffer = new byte[1024]; int len = -1; ByteArrayOutputStream outStream = new ByteArrayOutputStream(); while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); }//from w w w . j a va2s . c om byte[] data = outStream.toByteArray(); outStream.close(); inStream.close(); return data; }
From source file:com.couchbase.client.java.transcoder.TranscoderUtils.java
/** * Serializes the input into a ByteBuf.//from w w w.j av a 2s . c o m * * @param serializable the object to serialize. * @return the serialized object. * @throws Exception if something goes wrong during serialization. */ public static ByteBuf serialize(final Serializable serializable) throws Exception { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ; ObjectOutputStream os = new ObjectOutputStream(bos); os.writeObject(serializable); byte[] serialized = bos.toByteArray(); os.close(); bos.close(); return Unpooled.buffer().writeBytes(serialized); }
From source file:com.asual.lesscss.ResourceUtils.java
public static byte[] readBinaryFile(File source) throws IOException { byte[] result; try {/* w ww. j a va 2 s .c o m*/ ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); FileInputStream input = new FileInputStream(source); try { byte[] buffer = new byte[1024]; int bytesRead = -1; while ((bytesRead = input.read(buffer)) != -1) { byteStream.write(buffer, 0, bytesRead); } result = byteStream.toByteArray(); } finally { byteStream.close(); input.close(); } } catch (IOException e) { logger.error("Can't read '" + source.getAbsolutePath() + "'."); throw e; } return result; }