List of usage examples for java.io OutputStream flush
public void flush() throws IOException
From source file:net.grinder.util.LogCompressUtil.java
/** * Uncompress the given the {@link InputStream} into the given {@link OutputStream}. * /*from w w w . java 2 s. c o m*/ * @param inputStream * input stream of the compressed file * @param outputStream * file to be written * @param limit * the limit of the output */ public static void unCompress(InputStream inputStream, OutputStream outputStream, long limit) { ZipInputStream zipInputStream = null; try { zipInputStream = new ZipInputStream(inputStream); byte[] buffer = new byte[COMPRESS_BUFFER_SIZE]; int count = 0; long total = 0; checkNotNull(zipInputStream.getNextEntry(), "In zip, it should have at least one entry"); while ((count = zipInputStream.read(buffer, 0, COMPRESS_BUFFER_SIZE)) != -1) { total += count; if (total >= limit) { break; } outputStream.write(buffer, 0, count); } outputStream.flush(); } catch (IOException e) { LOGGER.error("Error occurs while uncompress"); LOGGER.error("Details", e); return; } finally { IOUtils.closeQuietly(zipInputStream); } }
From source file:de.tbuchloh.kiskis.persistence.PersistenceManager.java
/** * saves the file to disc.//from w ww . jav a 2s. c o m * * @param pwd * the associated password or null if it should be stored as plain text. * @param createBackup * true, if a copy of the doc should be created. * @throws KisKisException * if anything is wrong. */ private static void save(final TPMDocument doc, final ICryptoContext ctx, final boolean createBackup) throws CryptoException, PersistenceException { LOG.debug("saving ctx=" + ctx + ", createBackup=" + createBackup); try { assert ctx.getFile().equals(doc.getFile()); final StopWatch w = new StopWatch(); checkNewAttachments(doc); LOG.info("new attachments checked in " + w.reset()); if (createBackup) { createBackup(doc); LOG.info("backup created in " + w.reset()); } final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final XMLWriter writer = new XMLWriter(); writer.save(doc, bos); LOG.info("XML generated in " + w.reset()); final OutputStream os = new BufferedOutputStream(new FileOutputStream(doc.getFile())); ctx.encrypt(bos, os); os.flush(); os.close(); LOG.info("file written in " + w.reset()); createNewAttachments(doc); LOG.info("new attachments created in " + w.reset()); deleteOrphanedAttachmentFiles(doc); LOG.info("orphaned attachments cleaned in " + w.reset()); } catch (final IOException e) { throw new PersistenceException(e.getMessage(), e); } // set chmod on unix if possible final String chmod = "chmod 600 " + doc.getFile(); try { Runtime.getRuntime().exec(chmod); } catch (final IOException e) { LOG.info("cannot execute " + chmod + " ! msg=" + e.getMessage()); } }
From source file:org.hawkular.agent.monitor.util.Util.java
/** * Copies one stream to another, optionally closing the streams. * * @param input the data to copy/*from ww w . j av a2s .c o m*/ * @param output where to copy the data * @param closeStreams if true input and output will be closed when the method returns * @return the number of bytes copied * @throws RuntimeException if the copy failed */ public static long copyStream(InputStream input, OutputStream output, boolean closeStreams) throws RuntimeException { long numBytesCopied = 0; int bufferSize = BUFFER_SIZE; try { // make sure we buffer the input input = new BufferedInputStream(input, bufferSize); byte[] buffer = new byte[bufferSize]; for (int bytesRead = input.read(buffer); bytesRead != -1; bytesRead = input.read(buffer)) { output.write(buffer, 0, bytesRead); numBytesCopied += bytesRead; } output.flush(); } catch (IOException ioe) { throw new RuntimeException("Stream data cannot be copied", ioe); } finally { if (closeStreams) { try { output.close(); } catch (IOException ioe2) { // what to do? } try { input.close(); } catch (IOException ioe2) { // what to do? } } } return numBytesCopied; }
From source file:com.fota.Link.sdpApi.java
public static String getNcnInfo(String CTN) throws JDOMException { String resultStr = ""; String logData = ""; try {/*from www. j a v a 2 s.c o m*/ String endPointUrl = PropUtil.getPropValue("sdp.oif516.url"); String strRequest = "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' " + "xmlns:oas='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd'" + " xmlns:sdp='http://kt.com/sdp'>" + " <soapenv:Header>" + " <oas:Security>" + " <oas:UsernameToken>" + " <oas:Username>" + PropUtil.getPropValue("sdp.id") + "</oas:Username>" + " <oas:Password>" + PropUtil.getPropValue("sdp.pw") + "</oas:Password>" + " </oas:UsernameToken>" + " </oas:Security>" + " </soapenv:Header>" + " <soapenv:Body>" + " <sdp:getBasicUserInfoAndMarketInfoRequest>" + " <!--You may enterthe following 6 items in any order-->" + " <sdp:CALL_CTN>" + CTN + "</sdp:CALL_CTN>" + " </sdp:getBasicUserInfoAndMarketInfoRequest>\n" + " </soapenv:Body>\n" + "</soapenv:Envelope>"; logData = "\r\n---------- Get Ncn Req Info start ----------\r\n"; logData += " get Ncn Req Info - endPointUrl : " + endPointUrl; logData += "\r\n get Ncn Req Info - Content-type : text/xml;charset=utf-8"; logData += "\r\n get Ncn Req Info - RequestMethod : POST"; logData += "\r\n get Ncn Req Info - xml : " + strRequest; logData += "\r\n---------- Get Ncn Req Info end ----------"; logger.info(logData); // connection URL url = new URL(endPointUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Content-type", "text/xml;charset=utf-8"); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setDoInput(true); connection.connect(); // output OutputStream os = connection.getOutputStream(); // os.write(strRequest.getBytes(), 0, strRequest.length()); os.write(strRequest.getBytes("utf-8")); os.flush(); os.close(); // input InputStream is = connection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8")); String line = ""; String resValue = ""; String parseStr = ""; while ((line = br.readLine()) != null) { System.out.println(line); parseStr = line; } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource temp = new InputSource(); temp.setCharacterStream(new StringReader(parseStr)); Document doc = builder.parse(temp); //xml? NodeList list = doc.getElementsByTagName("*"); int i = 0; Element element; String contents; String contractNum = ""; String customerId = ""; while (list.item(i) != null) { element = (Element) list.item(i); if (element.hasChildNodes()) { contents = element.getFirstChild().getNodeValue(); System.out.println(element.getNodeName() + " / " + element.getFirstChild().getNodeName()); if (element.getNodeName().equals("sdp:NS_CONTRACT_NUM")) { // resultStr = element.getFirstChild().getNodeValue(); contractNum = element.getFirstChild().getNodeValue(); } if (element.getNodeName().equals("sdp:NS_CUSTOMER_ID")) { customerId = element.getFirstChild().getNodeValue(); } // System.out.println(" >>>>> " + contents); } i++; } // System.out.println("contractNum : " + contractNum + " / cusomerId : " + customerId); resultStr = getNcnFromContractnumAndCustomerId(contractNum, customerId); // System.out.println("ncn : " + resultStr); //resultStr = resValue; // resultStr = java.net.URLDecoder.decode(resultStr, "euc-kr"); connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } return resultStr; }
From source file:com.jcalvopinam.core.Unzipping.java
private static void joinAndUnzipFile(File inputFile, CustomFile customFile) throws IOException { ZipInputStream is = null;//from w ww . j a v a 2 s . co m File path = inputFile.getParentFile(); List<InputStream> fileInputStream = new ArrayList<>(); for (String fileName : path.list()) { if (fileName.startsWith(customFile.getFileName()) && fileName.endsWith(Extensions.ZIP.getExtension())) { fileInputStream.add(new FileInputStream(String.format("%s%s", customFile.getPath(), fileName))); System.out.println(String.format("File found: %s", fileName)); } } if (fileInputStream.size() > 0) { String fileNameOutput = String.format("%s%s", customFile.getPath(), customFile.getFileName()); OutputStream os = new BufferedOutputStream(new FileOutputStream(fileNameOutput)); try { System.out.println("Please wait while the files are joined: "); ZipEntry ze; for (InputStream inputStream : fileInputStream) { is = new ZipInputStream(inputStream); ze = is.getNextEntry(); customFile.setFileName(String.format("%s_%s", REBUILT, ze.getName())); byte[] buffer = new byte[CustomFile.BYTE_SIZE]; for (int readBytes; (readBytes = is.read(buffer, 0, CustomFile.BYTE_SIZE)) > -1;) { os.write(buffer, 0, readBytes); System.out.print("."); } } } finally { os.flush(); os.close(); is.close(); renameFinalFile(customFile, fileNameOutput); } } else { throw new FileNotFoundException("Error: The file not exist!"); } System.out.println("\nEnded process!"); }
From source file:net.grinder.util.LogCompressUtils.java
/** * Decompress the given the {@link InputStream} into the given {@link OutputStream}. * * @param inputStream input stream of the compressed file * @param outputStream file to be written * @param limit the limit of the output */// www . j av a 2s . c o m public static void decompress(InputStream inputStream, OutputStream outputStream, long limit) { ZipInputStream zipInputStream = null; try { zipInputStream = new ZipInputStream(inputStream); byte[] buffer = new byte[COMPRESS_BUFFER_SIZE]; int count; long total = 0; checkNotNull(zipInputStream.getNextEntry(), "In zip, it should have at least one entry"); do { while ((count = zipInputStream.read(buffer, 0, COMPRESS_BUFFER_SIZE)) != -1) { total += count; if (total >= limit) { break; } outputStream.write(buffer, 0, count); } } while (zipInputStream.getNextEntry() != null); outputStream.flush(); } catch (IOException e) { LOGGER.error("Error occurs while decompressing {}", e.getMessage()); LOGGER.debug("Details : ", e); } finally { IOUtils.closeQuietly(zipInputStream); } }
From source file:Main.java
/** * Write the entire contents of the supplied string to the given stream. This method always flushes and closes the stream when * finished./*from w ww. j av a2s . co m*/ * * @param input the content to write to the stream; may be null * @param stream the stream to which the content is to be written * @throws IOException * @throws IllegalArgumentException if the stream is null */ public static void write(InputStream input, OutputStream stream) throws IOException { boolean error = false; try { if (input != null) { byte[] buffer = new byte[1024]; try { int numRead = 0; while ((numRead = input.read(buffer)) > -1) { stream.write(buffer, 0, numRead); } } finally { input.close(); } } } catch (IOException e) { error = true; // this error should be thrown, even if there is an error flushing/closing stream throw e; } catch (RuntimeException e) { error = true; // this error should be thrown, even if there is an error flushing/closing stream throw e; } finally { try { stream.flush(); } catch (IOException e) { if (!error) throw e; } finally { try { stream.close(); } catch (IOException e) { if (!error) throw e; } } } }
From source file:net.orpiske.sdm.lib.net.Downloader.java
private static void copy(final Resource<InputStream> resource, final OutputStream output) throws IOException { InputStream input = resource.getPayload(); long i = 0;/*from ww w. j av a2 s . c o m*/ long total = resource.getResourceInfo().getSize(); for (i = 0; i < total; i++) { output.write(input.read()); if ((i % (1024 * 512)) == 0) { double percentComplete = 0; if (i > 0) { percentComplete = i / ((double) total / 100.0); } else { percentComplete = 0.0; } System.out.print("\r" + (int) percentComplete + "% complete (" + i + " of " + total + ")"); } } System.out.print("\r100% complete (" + i + " of " + total + ")\n"); output.flush(); }
From source file:com.androidrocks.bex.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. *///from ww w . ja va2 s.co 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; }
From source file:Files.java
/** * Attempt to flush an <tt>OutputStream</tt>. * * @param stream <tt>OutputStream</tt> to attempt to flush. * @return <tt>True</tt> if stream was flushed (or stream was null), * or <tt>false</tt> if an exception was thrown. *//*from www. j a va 2s . c o m*/ public static boolean flush(final OutputStream stream) { // do not attempt to close null stream, but return sucess if (stream == null) { return true; } boolean success = true; try { stream.flush(); } catch (IOException e) { success = false; } return success; }