/** @Method: packData @Description: ���Ҫ���͵���� */ private void packData() { currentBitmap = BitmapList[firstView]; ByteArrayOutputStream stream1 = new ByteArrayOutputStream(); // stream1 currentBitmap.compress( Bitmap.CompressFormat.PNG, 1, stream1); // compress to which format you want byte[] byte_arr = stream1.toByteArray(); // stream1 to byte try { stream1.close(); stream1 = null; } catch (IOException e1) { e1.printStackTrace(); } String image_str = Base64.encodeBytes(byte_arr); // byte to string Bitmap smallcurrentBitmap; float wRatio = (float) (currentBitmap.getWidth() / 100.0); float hRatio = (float) (currentBitmap.getHeight() / 100.0); if (wRatio > 1 && hRatio > 1) // ����ָ����С������С��Ӧ�ı��� { float scaleTemp; if (wRatio > hRatio) scaleTemp = hRatio; else scaleTemp = wRatio; wRatio = currentBitmap.getWidth() / scaleTemp; hRatio = currentBitmap.getHeight() / scaleTemp; int h = (int) wRatio; int w = (int) hRatio; smallcurrentBitmap = Bitmap.createScaledBitmap(currentBitmap, h, w, false); } else smallcurrentBitmap = currentBitmap; ByteArrayOutputStream stream2 = new ByteArrayOutputStream(); // stream2 smallcurrentBitmap.compress( Bitmap.CompressFormat.PNG, 50, stream2); // compress to which format you want smallcurrentBitmap.recycle(); byte_arr = stream2.toByteArray(); // stream2 to byte try { stream2.close(); stream2 = null; } catch (IOException e) { e.printStackTrace(); } String smallimage_str = Base64.encodeBytes(byte_arr); // byte to string nameValuePairs.add(new BasicNameValuePair("protocol", "upload")); // ��װ��ֵ�� nameValuePairs.add(new BasicNameValuePair("id", LoginActivity.mineID)); nameValuePairs.add(new BasicNameValuePair("albumName", choosedAlbum)); nameValuePairs.add( new BasicNameValuePair( "imageName", PhotoAlbumActivity.AlbumsFloderName.get(AlbumName).get(currentNum))); Log.d("debug", PhotoAlbumActivity.AlbumsFloderName.get(AlbumName).get(currentNum)); nameValuePairs.add(new BasicNameValuePair("image", image_str)); nameValuePairs.add(new BasicNameValuePair("smallImage", smallimage_str)); System.gc(); }
public void run() { URL url; Base64Encoder base64 = new Base64Encoder(); try { url = new URL(urlString); } catch (MalformedURLException e) { System.err.println("Invalid URL"); return; } try { conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Authorization", "Basic " + base64.encode(user + ":" + pass)); httpIn = new BufferedInputStream(conn.getInputStream(), 8192); } catch (IOException e) { System.err.println("Unable to connect: " + e.getMessage()); return; } int prev = 0; int cur = 0; try { while (keepAlive && (cur = httpIn.read()) >= 0) { if (prev == 0xFF && cur == 0xD8) { jpgOut = new ByteArrayOutputStream(8192); jpgOut.write((byte) prev); } if (jpgOut != null) { jpgOut.write((byte) cur); } if (prev == 0xFF && cur == 0xD9) { synchronized (curFrame) { curFrame = jpgOut.toByteArray(); } frameAvailable = true; jpgOut.close(); } prev = cur; } } catch (IOException e) { System.err.println("I/O Error: " + e.getMessage()); } try { jpgOut.close(); httpIn.close(); } catch (IOException e) { System.err.println("Error closing streams: " + e.getMessage()); } conn.disconnect(); }
@After public void tearDown() throws IOException { out.close(); if (tajoCli != null) { tajoCli.close(); } }
public static String loadAFileToString(File f) { InputStream is = null; String ret = null; try { is = new BufferedInputStream(new FileInputStream(f)); long contentLength = f.length(); ByteArrayOutputStream outstream = new ByteArrayOutputStream(contentLength > 0 ? (int) contentLength : 1024); byte[] buffer = new byte[4096]; int len; while ((len = is.read(buffer)) > 0) { outstream.write(buffer, 0, len); } outstream.close(); ret = new String(outstream.toByteArray(), "utf-8"); } catch (IOException e) { ret = ""; } finally { if (is != null) { try { is.close(); } catch (Exception e) { } } } return ret; }
/** * This is Bob's original test, re-written only to allow it to execute as a normal junit test * within Eclipse. */ @Test public void origTestOfRewritingMHLDtoSameBib() throws IOException { String mhldRecFileName = testDataParentPath + File.separator + "summaryHld_1-1000.mrc"; String bibRecFileName = testDataParentPath + File.separator + "u335.mrc"; InputStream inStr = null; ByteArrayOutputStream resultMrcOutStream = new ByteArrayOutputStream(); String[] mergeMhldArgs = new String[] {"-s", mhldRecFileName, bibRecFileName}; // call the code for mhldfile summaryHld_1-1000.mrc and bibfile u335.mrc CommandLineUtils.runCommandLineUtil( MERGE_MHLD_CLASS_NAME, MAIN_METHOD_NAME, inStr, resultMrcOutStream, mergeMhldArgs); RecordTestingUtils.assertMarcRecsEqual(mergedSummaryHoldingsOutput, resultMrcOutStream); // Now merge record again to test the deleting of existing summary holdings info ByteArrayInputStream mergedMarcBibRecAsInStream = new ByteArrayInputStream(resultMrcOutStream.toByteArray()); resultMrcOutStream.close(); resultMrcOutStream = new ByteArrayOutputStream(); // do the merge by piping the bib record in to the merge class CommandLineUtils.runCommandLineUtil( MERGE_MHLD_CLASS_NAME, MAIN_METHOD_NAME, mergedMarcBibRecAsInStream, resultMrcOutStream, new String[] {"-s", mhldRecFileName}); RecordTestingUtils.assertMarcRecsEqual(mergedSummaryHoldingsOutput, resultMrcOutStream); System.out.println("Test origTestOfRewritingMHLDtoSameBib() successful"); }
// #sijapp cond.if (protocols_MRIM is "true") or (protocols_VK is "true") or (protocols_ICQ is // "true") # private byte[] read(InputStream in, int length) throws IOException { if (0 == length) { return null; } if (0 < length) { byte[] bytes = new byte[length]; int readCount = 0; while (readCount < bytes.length) { int c = in.read(bytes, readCount, bytes.length - readCount); if (-1 == c) break; readCount += c; } return bytes; } ByteArrayOutputStream bytes = new ByteArrayOutputStream(); for (int i = 0; i < 100 * 1024; ++i) { int ch = in.read(); if (-1 == ch) break; bytes.write(ch); } byte[] content = bytes.toByteArray(); bytes.close(); return content; }
/** * compare the byte-array representation of two TaskObjects. * * @param f TaskObject * @param s TaskObject * @return true if the two arguments have the same byte-array */ private boolean sameBytes(TaskObject f, TaskObject s) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = null; try { out = new ObjectOutputStream(bos); out.writeObject(f); byte[] fs = bos.toByteArray(); out.writeObject(s); byte[] ss = bos.toByteArray(); if (fs.length != ss.length) return false; for (int i = 0; i < fs.length; i++) { if (fs[i] != ss[i]) return false; } return true; } catch (IOException e) { e.printStackTrace(); return false; } finally { if (out != null) { try { out.close(); } catch (IOException e) { // ignore } try { bos.close(); } catch (IOException e) { // ignore } } } }
/** * Serializes the passed object to a byte array, returning a zero byte array if the passed object * is null, or fails serialization * * @param arg The object to serialize * @return the serialized object */ public static byte[] serializeNoCompress(Object arg) { if (arg == null) return new byte[] {}; ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(baos); oos.writeObject(arg); oos.flush(); baos.flush(); return baos.toByteArray(); } catch (Exception ex) { return new byte[] {}; } finally { try { baos.close(); } catch (Exception ex) { /* No Op */ } if (oos != null) try { oos.close(); } catch (Exception ex) { /* No Op */ } } }
/** * Git advertise 요청을 처리한다. * * <p>when: {@link controllers.GitApp#service(String, String, String, boolean)}에서 사용한다. * * @param project * @param service * @param response * @return * @throws IOException * @see <a * href="https://www.kernel.org/pub/software/scm/git/docs/git-upload-pack.html">git-upload-pack</a> * @see <a * href="https://www.kernel.org/pub/software/scm/git/docs/git-receive-pack.html">git-receive-pack</a> */ public static byte[] gitAdvertise(Project project, String service, Response response) throws IOException { response.setContentType("application/x-" + service + "-advertisement"); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); PacketLineOut packetLineOut = new PacketLineOut(byteArrayOutputStream); packetLineOut.writeString("# service=" + service + "\n"); packetLineOut.end(); PacketLineOutRefAdvertiser packetLineOutRefAdvertiser = new PacketLineOutRefAdvertiser(packetLineOut); Repository repository = createGitRepository(project); if (service.equals("git-upload-pack")) { UploadPack uploadPack = new UploadPack(repository); uploadPack.setBiDirectionalPipe(false); uploadPack.sendAdvertisedRefs(packetLineOutRefAdvertiser); } else if (service.equals("git-receive-pack")) { ReceivePack receivePack = new ReceivePack(repository); receivePack.sendAdvertisedRefs(packetLineOutRefAdvertiser); } byteArrayOutputStream.close(); return byteArrayOutputStream.toByteArray(); }
public static String postXml(String url, String xmlData) { HttpPost post = new HttpPost(url); InputStream is = null; ByteArrayOutputStream baos = null; try { StringEntity entity = new StringEntity(xmlData); post.setEntity(entity); post.setHeader("Content-Type", "text/xml;charset=UTF-8"); HttpResponse response = httpClient.execute(post); is = response.getEntity().getContent(); baos = new ByteArrayOutputStream(); byte[] data = new byte[1024]; int count = is.read(data); while (count != -1) { baos.write(data, 0, count); count = is.read(data); } return baos.toString(); } catch (Exception e) { e.printStackTrace(); } finally { if (is != null) try { is.close(); } catch (Exception ignore) { } if (baos != null) try { baos.close(); } catch (Exception ignore) { } } return null; }
/** * Pack the structure to the network message * * @return the network message in byte[] * @throws MeasurementError stream writer failed */ public byte[] getByteArray() throws MeasurementError { ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); DataOutputStream dataOut = new DataOutputStream(byteOut); try { dataOut.writeInt(type); dataOut.writeInt(burstCount); dataOut.writeInt(packetNum); dataOut.writeInt(intervalNum); dataOut.writeLong(timestamp); dataOut.writeInt(packetSize); dataOut.writeInt(seq); dataOut.writeInt(udpInterval); } catch (IOException e) { throw new MeasurementError("Create rawpacket failed! " + e.getMessage()); } byte[] rawPacket = byteOut.toByteArray(); try { byteOut.close(); } catch (IOException e) { throw new MeasurementError("Error closing outputstream!"); } return rawPacket; }
/** * reads the content of an existing file using the current domain * * @param domain The namespace used to identify the application domain (1st level directory) to * use * @param path The path relative to the domain for the file * @param offset the offset from the beginning of the file. * @param len The length of the block in bytes * @return The contents of the file */ public byte[] readByteFromFile(String path, long offset, int len) throws EOFException, FileAccessException { try { if (_isLocal) { File tmpFile = new File(_rootFile.getCanonicalPath() + File.separatorChar + path); if (tmpFile.isFile()) { RandomAccessFile raf = new RandomAccessFile(tmpFile, "r"); byte[] buffer = new byte[len]; raf.seek(offset); int totalByteRead = 0; ByteArrayOutputStream out = new ByteArrayOutputStream(); int result = 0; while (totalByteRead < len && raf.getFilePointer() < raf.length()) { result = raf.read(buffer, 0, (len - totalByteRead)); if (result != -1) { out.write(buffer, 0, result); totalByteRead += result; } else if (totalByteRead == 0) throw new EOFException("End of file reached!"); else break; } raf.close(); out.flush(); out.close(); return out.toByteArray(); } else throw new FileAccessException("Path is not a file"); } else return _remote.readByteFromFile(_domain, path, offset, len); } catch (EOFException eofe) { throw eofe; } catch (FileAccessException fae) { throw fae; } catch (Exception e) { throw new FileAccessException(e); } }
/** execute method之后,取返回的inputstream */ private static ByteArrayInputStream execute4InputStream(HttpClient client) throws Exception { int statusCode = client.getResponseCode(); if (statusCode != HttpURLConnection.HTTP_OK) { throw new EnvException("Method failed: " + statusCode); } InputStream in = client.getResponseStream(); if (in == null) { return null; } ByteArrayOutputStream out = new ByteArrayOutputStream(); try { Utils.copyBinaryTo(in, out); // 看一下传过来的byte[]是不是DesignProcessor.INVALID,如果是的话,就抛Exception byte[] bytes = out.toByteArray(); // carl:格式一致传中文 String message = new String(bytes, EncodeConstants.ENCODING_UTF_8); if (ComparatorUtils.equals(message, RemoteDeziConstants.NO_SUCH_RESOURCE)) { return null; } else if (ComparatorUtils.equals(message, RemoteDeziConstants.INVALID_USER)) { throw new EnvException(RemoteDeziConstants.INVALID_USER); } else if (ComparatorUtils.equals(message, RemoteDeziConstants.FILE_LOCKED)) { JOptionPane.showMessageDialog(null, Inter.getLocText("FR-Designer_file-is-locked")); return null; } else if (message.startsWith(RemoteDeziConstants.RUNTIME_ERROR_PREFIX)) { } return new ByteArrayInputStream(bytes); } finally { in.close(); out.close(); client.release(); } }
public synchronized void close() throws IOException { if (isOutputOpen) { super.close(); payload = toByteArray(); isOutputOpen = false; } }
/* transform manifest in an array of byte if any code error, exit else if any error, show dialog, then return nil */ public static byte[] s_toByteArray(Manifest man, Frame frmOwner) { String strMethod = _f_s_strClass + "s_toByteArray(...)"; if (man == null) { MySystem.s_printOutExit(strMethod, "nil man"); } ByteArrayOutputStream baoBuffer = new ByteArrayOutputStream(); try { man.write(baoBuffer); baoBuffer.flush(); baoBuffer.close(); } catch (IOException excIO) { excIO.printStackTrace(); MySystem.s_printOutExit(strMethod, "excIO caught"); String strBody = "Got IO exception"; OPAbstract.s_showDialogError(frmOwner, strBody); return null; } return baoBuffer.toByteArray(); }
/** * Reads a base class overrride from a resource file * * @param binaryClassName * @param fileName */ private void registerBaseClassOverride(String binaryClassName, String fileName) { try { Method mDefineClass = ClassLoader.class.getDeclaredMethod( "defineClass", String.class, byte[].class, int.class, int.class); mDefineClass.setAccessible(true); InputStream resourceInputStream = LiteLoader.class.getResourceAsStream("/classes/" + fileName + ".bin"); if (resourceInputStream != null) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); for (int readBytes = resourceInputStream.read(); readBytes >= 0; readBytes = resourceInputStream.read()) { outputStream.write(readBytes); } byte[] data = outputStream.toByteArray(); outputStream.close(); resourceInputStream.close(); logger.info("Defining class override for " + binaryClassName); mDefineClass.invoke( Minecraft.class.getClassLoader(), binaryClassName, data, 0, data.length); } else { logger.info("Error defining class override for " + binaryClassName + ", file not found"); } } catch (Throwable th) { logger.log(Level.WARNING, "Error defining class override for " + binaryClassName, th); } }
/** * Creates an object using serialization. * * @return the new object */ public Object create() { ByteArrayOutputStream baos = new ByteArrayOutputStream(512); ByteArrayInputStream bais = null; try { ObjectOutputStream out = new ObjectOutputStream(baos); out.writeObject(iPrototype); bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream in = new ObjectInputStream(bais); return in.readObject(); } catch (ClassNotFoundException ex) { throw new FunctorException(ex); } catch (IOException ex) { throw new FunctorException(ex); } finally { try { if (bais != null) { bais.close(); } } catch (IOException ex) { // ignore } try { if (baos != null) { baos.close(); } } catch (IOException ex) { // ignore } } }
public JilterStatus eom(JilterEOMActions eomActions, Properties properties) { logger.debug("jilter eom()"); try { bos.close(); // close stream } catch (IOException io) { logger.error("jilter failed to close io stream during eom", io); } byte[] messageBytes = bos.toByteArray(); bos = new ByteArrayOutputStream(); ByteArrayInputStream bis = new ByteArrayInputStream(messageBytes); try { logger.debug("jilter store callback execute"); Config.getStopBlockFactory() .detectBlock("milter server", Thread.currentThread(), this, IDLE_TIMEOUT); callback.store(bis, host); logger.debug("jilter store callback finished"); } catch (ArchiveException e) { logger.error("failed to store the message via milter", e); if (e.getRecoveryDirective() == ArchiveException.RecoveryDirective.REJECT) { logger.debug("jilter reject"); return JilterStatus.SMFIS_REJECT; } else if (e.getRecoveryDirective() == ArchiveException.RecoveryDirective.RETRYLATER) { logger.debug("jilter temp fail"); return JilterStatus.SMFIS_TEMPFAIL; } } catch (Throwable oome) { logger.error("failed to store message:" + oome.getMessage(), oome); return JilterStatus.SMFIS_REJECT; } finally { Config.getStopBlockFactory().endDetectBlock(Thread.currentThread()); } return JilterStatus.SMFIS_CONTINUE; }
public static void main(String[] args) throws Exception { // create the keys KeyPair pair = Utils.generateRSAKeyPair(); // create the input stream ByteArrayOutputStream bOut = new ByteArrayOutputStream(); if (outputFormat.equals(DER)) { bOut.write(X509V1CreateExample.generateV1Certificate(pair).getEncoded()); } else if (outputFormat.equals(PEM)) { PEMWriter pemWriter = new PEMWriter(new OutputStreamWriter(bOut)); pemWriter.writeObject(X509V1CreateExample.generateV1Certificate(pair)); pemWriter.close(); } bOut.close(); // Print the contents of bOut System.out.println(outputFormat.equals(DER) ? "DER-format:" : "PEM-format:"); System.out.println(Utils.toString(bOut.toByteArray())); InputStream in = new ByteArrayInputStream(bOut.toByteArray()); // create the certificate factory CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); // read the certificate X509Certificate x509Cert = (X509Certificate) fact.generateCertificate(in); System.out.println("issuer: " + x509Cert.getIssuerX500Principal()); }
public void run() { byte[] tmp = new byte[10000]; int read; try { FileInputStream fis = new FileInputStream(fileToSend.getFile()); read = fis.read(tmp); while (read != -1) { baos.write(tmp, 0, read); read = fis.read(tmp); System.out.println(read); } fis.close(); baos.writeTo(sWriter); sWriter.flush(); baos.flush(); baos.close(); System.out.println("fileSent"); } catch (IOException e) { e.printStackTrace(); } finally { this.closeSocket(); } }
/** * 根据文件以byte[]形式返回文件的数据 * * @param file * @return */ public static byte[] getFileData(File file) { FileInputStream in = null; ByteArrayOutputStream out = null; try { in = new FileInputStream(file); out = new ByteArrayOutputStream(BUFFER_SIZE); int byteCount = 0; byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead = -1; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); byteCount += bytesRead; } out.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException ex) { ex.printStackTrace(); } } return out.toByteArray(); }
private String getUrlContent(CachedUrl url) throws IOException { InputStream content = url.getUnfilteredInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); StreamUtil.copy(content, baos); content.close(); String contentStr = new String(baos.toByteArray()); baos.close(); return contentStr; }
@Test public void writeToOutputStream() throws IOException { XMLDocument doc = db.createFolder("/top").documents().load(Name.create(db, "foo"), Source.xml("<root/>")); ByteArrayOutputStream out = new ByteArrayOutputStream(); doc.write(out); out.close(); assertEquals("<root/>", out.toString()); }
/** Attempt to free memory and remove references. */ public void cleanUp() { mBitmap.recycle(); mBitmap = null; try { mStream.close(); } catch (IOException e) { // ignore } mStream = null; }
public byte[] getActualByteArray(Annotation annotation) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); AnnotationDataOutputStream writer = new AnnotationDataOutputStream(new DataOutputStream(output), new Version("0.9")); writer.write(annotation); output.close(); return output.toByteArray(); }
/** * Read an InputStream into a byte array. * * @param is InputStream * @return byte array */ public static byte[] inputStreamToByteArray(InputStream is) { try { final ByteArrayOutputStream os = new ByteArrayOutputStream(); copyStream(new BufferedInputStream(is), os); os.close(); return os.toByteArray(); } catch (Exception e) { throw new OXFException(e); } }
public static byte[] toByteArray(Classifier classifier) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(classifier); oos.close(); baos.close(); return baos.toByteArray(); }
public static int sizeInBytes(Object obj) throws IOException { ByteArrayOutputStream byteObject = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteObject); objectOutputStream.writeObject(obj); objectOutputStream.flush(); objectOutputStream.close(); byteObject.close(); return byteObject.toByteArray().length; }
protected byte[] uncompressBlockUsingStream(InputStream in) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(_compressed.length); byte[] buffer = new byte[4000]; int count; while ((count = in.read(buffer)) >= 0) { out.write(buffer, 0, count); } in.close(); out.close(); return out.toByteArray(); }
public static byte[] readInput(InputStream in) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); int len = 0; byte[] buffer = new byte[1024]; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } out.close(); in.close(); return out.toByteArray(); }