List of usage examples for java.io OutputStream flush
public void flush() throws IOException
From source file:Streams.java
/** * Copies the contents of the given {@link InputStream} * to the given {@link OutputStream}./*ww w .ja v a 2s .c o m*/ * @param pIn The input stream, which is being read. * It is guaranteed, that {@link InputStream#close()} is called * on the stream. * @param pOut The output stream, to which data should * be written. May be null, in which case the input streams * contents are simply discarded. * @param pClose True guarantees, that {@link OutputStream#close()} * is called on the stream. False indicates, that only * {@link OutputStream#flush()} should be called finally. * @param pBuffer Temporary buffer, which is to be used for * copying data. * @return Number of bytes, which have been copied. * @throws IOException An I/O error occurred. */ public static long copy(InputStream pIn, OutputStream pOut, boolean pClose, byte[] pBuffer) throws IOException { OutputStream out = pOut; InputStream in = pIn; try { long total = 0; for (;;) { int res = in.read(pBuffer); if (res == -1) { break; } if (res > 0) { total += res; if (out != null) { out.write(pBuffer, 0, res); } } } if (out != null) { if (pClose) { out.close(); } else { out.flush(); } out = null; } in.close(); in = null; return total; } finally { if (in != null) { try { in.close(); } catch (Throwable t) { /* Ignore me */ } } if (pClose && out != null) { try { out.close(); } catch (Throwable t) { /* Ignore me */ } } } }
From source file:dk.netarkivet.common.utils.StreamUtils.java
/** * Write document tree to stream. Note, the stream is flushed, but not * closed.// ww w .j a va 2 s.co m * * @param doc the document tree to save. * @param os the stream to write xml to * @throws IOFailure On trouble writing XML to stream. */ public static void writeXmlToStream(Document doc, OutputStream os) { ArgumentNotValid.checkNotNull(doc, "Document doc"); ArgumentNotValid.checkNotNull(doc, "OutputStream os"); XMLWriter xwriter = null; try { try { OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding(UTF8_CHARSET); xwriter = new XMLWriter(os, format); xwriter.write(doc); } finally { if (xwriter != null) { xwriter.close(); } os.flush(); } } catch (IOException e) { String errMsg = "Unable to write XML to stream"; log.warn(errMsg, e); throw new IOFailure(errMsg, e); } }
From source file:Main.java
public static String customrequest(String url, HashMap<String, String> params, String method) { try {//w ww. jav a2s .com URL postUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) postUrl.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setConnectTimeout(5 * 1000); conn.setRequestMethod(method); conn.setUseCaches(false); conn.setInstanceFollowRedirects(true); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)"); conn.connect(); OutputStream out = conn.getOutputStream(); StringBuilder sb = new StringBuilder(); if (null != params) { int i = params.size(); for (Map.Entry<String, String> entry : params.entrySet()) { if (i == 1) { sb.append(entry.getKey() + "=" + entry.getValue()); } else { sb.append(entry.getKey() + "=" + entry.getValue() + "&"); } i--; } } String content = sb.toString(); out.write(content.getBytes("UTF-8")); out.flush(); out.close(); InputStream inStream = conn.getInputStream(); String result = inputStream2String(inStream); conn.disconnect(); return result; } catch (Exception e) { // TODO: handle exception } return null; }
From source file:com.xqdev.jam.MLJAM.java
private static void sendBinaryResponse(HttpServletResponse res, byte[] bytes) throws IOException { res.setContentType("application/binary-encoded"); OutputStream out = res.getOutputStream(); // care to handle errors later? out.write(bytes);/*from www. j a v a 2 s. c om*/ out.flush(); }
From source file:com.microsoft.azure.hdinsight.common.StreamUtil.java
public static File getResourceFile(String resource) throws IOException { File file = null;//from w w w .jav a 2 s.c o m URL res = streamUtil.getClass().getResource(resource); if (res.toString().startsWith("jar:")) { InputStream input = null; OutputStream out = null; try { input = streamUtil.getClass().getResourceAsStream(resource); file = File.createTempFile(String.valueOf(new Date().getTime()), ".tmp"); out = new FileOutputStream(file); int read; byte[] bytes = new byte[1024]; while ((read = input.read(bytes)) != -1) { out.write(bytes, 0, read); } } finally { if (input != null) { input.close(); } if (out != null) { out.flush(); out.close(); } if (file != null) { file.deleteOnExit(); } } } else { file = new File(res.getFile()); } return file; }
From source file:com.openkm.util.PDFUtils.java
/** * Merge several PDFs into a new one// w ww. j a v a 2s . c o m */ public static void merge(List<InputStream> inputs, OutputStream output) throws IOException, DocumentException { Document document = new Document(); try { PdfSmartCopy copy = new PdfSmartCopy(document, output); document.open(); for (InputStream is : inputs) { PdfReader reader = new PdfReader(is); for (int i = 1; i <= reader.getNumberOfPages(); i++) { copy.addPage(copy.getImportedPage(reader, i)); } } output.flush(); document.close(); } finally { IOUtils.closeQuietly(output); } }
From source file:eu.scape_project.planning.xml.ProjectExportAction.java
/** * Dumps binary data to provided file. It results in an XML file with a * single element: data.// ww w .j av a2s . c o m * * @param id * @param data * @param f * @param encoder * @throws IOException */ private static void writeBinaryData(int id, InputStream data, File f) throws IOException { XMLOutputFactory factory = XMLOutputFactory.newInstance(); try { XMLStreamWriter writer = factory.createXMLStreamWriter(new FileWriter(f)); writer.writeStartDocument(PlanXMLConstants.ENCODING, "1.0"); writer.writeStartElement("data"); writer.writeAttribute("id", "" + id); Base64InputStream base64EncodingIn = new Base64InputStream(data, true, PlanXMLConstants.BASE64_LINE_LENGTH, PlanXMLConstants.BASE64_LINE_BREAK); OutputStream out = new WriterOutputStream(new XMLStreamContentWriter(writer), PlanXMLConstants.ENCODING); // read the binary data and encode it on the fly IOUtils.copy(base64EncodingIn, out); out.flush(); // all data is written - end writer.writeEndElement(); writer.writeEndDocument(); writer.flush(); writer.close(); } catch (XMLStreamException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.iStudy.Study.Renren.Util.java
private static HttpURLConnection sendFormdata(String reqUrl, Bundle parameters, String fileParamName, String filename, String contentType, byte[] data) { HttpURLConnection urlConn = null; try {/*from w ww .j a va 2 s. c om*/ URL url = new URL(reqUrl); urlConn = (HttpURLConnection) url.openConnection(); urlConn.setRequestMethod("POST"); urlConn.setConnectTimeout(5000);// ??jdk urlConn.setReadTimeout(5000);// ??jdk 1.5??,? urlConn.setDoOutput(true); urlConn.setRequestProperty("connection", "keep-alive"); String boundary = "-----------------------------114975832116442893661388290519"; // urlConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); boundary = "--" + boundary; StringBuffer params = new StringBuffer(); if (parameters != null) { for (Iterator<String> iter = parameters.keySet().iterator(); iter.hasNext();) { String name = iter.next(); String value = parameters.getString(name); params.append(boundary + "\r\n"); params.append("Content-Disposition: form-data; name=\"" + name + "\"\r\n\r\n"); // params.append(URLEncoder.encode(value, "UTF-8")); params.append(value); params.append("\r\n"); } } StringBuilder sb = new StringBuilder(); sb.append(boundary); sb.append("\r\n"); sb.append("Content-Disposition: form-data; name=\"" + fileParamName + "\"; filename=\"" + filename + "\"\r\n"); sb.append("Content-Type: " + contentType + "\r\n\r\n"); byte[] fileDiv = sb.toString().getBytes(); byte[] endData = ("\r\n" + boundary + "--\r\n").getBytes(); byte[] ps = params.toString().getBytes(); OutputStream os = urlConn.getOutputStream(); os.write(ps); os.write(fileDiv); os.write(data); os.write(endData); os.flush(); os.close(); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } return urlConn; }
From source file:TripleDES.java
/** * Use the specified TripleDES key to decrypt bytes ready from the input * stream and write them to the output stream. This method uses uses Cipher * directly to show how it can be done without CipherInputStream and * CipherOutputStream.//from ww w .j a v a 2 s . c o m */ public static void decrypt(SecretKey key, InputStream in, OutputStream out) throws NoSuchAlgorithmException, InvalidKeyException, IOException, IllegalBlockSizeException, NoSuchPaddingException, BadPaddingException { // Create and initialize the decryption engine Cipher cipher = Cipher.getInstance("DESede"); cipher.init(Cipher.DECRYPT_MODE, key); // Read bytes, decrypt, and write them out. byte[] buffer = new byte[2048]; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { out.write(cipher.update(buffer, 0, bytesRead)); } // Write out the final bunch of decrypted bytes out.write(cipher.doFinal()); out.flush(); }
From source file:com.siahmsoft.soundroid.sdk7.util.ImageUtilities.java
/** * Loads an image from the specified URL with the specified cookie. * * @param url The URL of the image to load. * @param cookie The cookie to use to load the image. * * @return The image at the specified URL or null if an error occured. *//*www.j a va 2s .c o m*/ public static ExpiringBitmap load(String url, String cookie) { ExpiringBitmap expiring = new ExpiringBitmap(); final HttpGet get = new HttpGet(url); if (cookie != null) { get.setHeader("cookie", cookie); } HttpEntity entity = null; try { final HttpResponse response = HttpManager.execute(get); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { setLastModified(expiring, response); entity = response.getEntity(); InputStream in = null; OutputStream out = null; try { in = entity.getContent(); if (FLAG_DECODE_BITMAP_WITH_SKIA) { expiring.bitmap = BitmapFactory.decodeStream(in); } else { final ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); out = new BufferedOutputStream(dataStream, IOUtilities.IO_BUFFER_SIZE); IOUtilities.copy(in, out); out.flush(); final byte[] data = dataStream.toByteArray(); expiring.bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); } } catch (IOException e) { android.util.Log.e(LOG_TAG, "Could not load image from " + url, e); } finally { IOUtilities.closeStream(in); IOUtilities.closeStream(out); } } } catch (IOException e) { android.util.Log.e(LOG_TAG, "Could not load image from " + url, e); } finally { if (entity != null) { try { entity.consumeContent(); } catch (IOException e) { android.util.Log.e(LOG_TAG, "Could not load image from " + url, e); } } } return expiring; }