List of usage examples for java.io OutputStream close
public void close() throws IOException
From source file:com.ibm.jaggr.core.util.CopyUtil.java
public static void copy(Reader reader, OutputStream out) throws IOException { InputStream in = new ReaderInputStream(reader, "UTF-8"); //$NON-NLS-1$ try {/*from ww w .ja v a 2 s .c o m*/ IOUtils.copy(in, out); } finally { try { in.close(); } catch (Exception ignore) { } try { out.close(); } catch (Exception ignore) { } } }
From source file:com.inmobi.messaging.consumer.util.FileUtil.java
public static void gzip(Path src, Path target, Configuration conf) throws IOException { FileSystem fs = FileSystem.get(conf); FSDataOutputStream out = fs.create(target); GzipCodec gzipCodec = (GzipCodec) ReflectionUtils.newInstance(GzipCodec.class, conf); Compressor gzipCompressor = CodecPool.getCompressor(gzipCodec); OutputStream compressedOut = gzipCodec.createOutputStream(out, gzipCompressor); FSDataInputStream in = fs.open(src); try {/*w w w.j a v a 2s. c o m*/ IOUtils.copyBytes(in, compressedOut, conf); } catch (Exception e) { LOG.error("Error in compressing ", e); } finally { in.close(); CodecPool.returnCompressor(gzipCompressor); compressedOut.close(); out.close(); } }
From source file:com.amazonaws.encryptionsdk.internal.TestIOUtils.java
public static void copyInStreamToOutStream(final InputStream inStream, final OutputStream outStream, final int readLen) throws IOException { final byte[] readBuffer = new byte[readLen]; int actualRead = 0; while (actualRead >= 0) { outStream.write(readBuffer, 0, actualRead); actualRead = inStream.read(readBuffer); }//from w w w . j a v a 2s. c om inStream.close(); outStream.close(); }
From source file:com.aqnote.shared.cryptology.cert.io.PKCSWriter.java
public static void storePKCS10File(PKCS10CertificationRequest csr, OutputStream ostream) throws Exception { StringBuilder csrString = new StringBuilder(CSR_BEGIN + _N); csrString.append(Base64.encodeBase64String(csr.getEncoded()) + _N); csrString.append(CSR_END);/*ww w .j a va 2 s .co m*/ ostream.write(csrString.toString().getBytes()); ostream.close(); }
From source file:Main.java
/** * //from w w w.ja va2s . c o m * @param context * @param backupFolder * @param db_name * @return */ public static boolean backupDB(Context context, String backupFolder, String db_name) { boolean result = false; try { String current_date = DateToString(GetToday(), "dd-MM-yyyy"); File data = Environment.getDataDirectory(); File sdcard = new File(Environment.getExternalStorageDirectory(), backupFolder + "/"); sdcard.mkdirs(); if (sdcard.canWrite()) { String currentDBPath = "//data//" + context.getPackageName() + "//databases//" + db_name + ""; String backupDBPath = "backup_" + db_name + "_" + current_date + ".db"; File currentDB = new File(data, currentDBPath); File backupDB = new File(sdcard, backupDBPath); if (currentDB.exists()) { InputStream input = new FileInputStream(currentDB); OutputStream output = new FileOutputStream(backupDB); byte[] buffer = new byte[1024]; int length; while ((length = input.read(buffer)) > 0) { output.write(buffer, 0, length); } output.flush(); output.close(); input.close(); result = true; } } } catch (Exception e) { Log.e(TAG, e.getMessage()); } return result; }
From source file:br.org.ipti.guigoh.util.DownloadService.java
public static synchronized void downloadFile(File file, String mimeType) { FacesContext facesContext = FacesContext.getCurrentInstance(); ExternalContext context = facesContext.getExternalContext(); HttpServletResponse response = (HttpServletResponse) context.getResponse(); response.setHeader("Content-Disposition", "attachment;filename=\"" + file.getName() + "\""); response.setContentLength((int) file.length()); response.setContentType(mimeType);/* w w w .jav a 2 s . c om*/ try { OutputStream out; try (FileInputStream in = new FileInputStream(file)) { out = response.getOutputStream(); byte[] buf = new byte[(int) file.length()]; int count; while ((count = in.read(buf)) >= 0) { out.write(buf, 0, count); } } out.flush(); out.close(); facesContext.responseComplete(); } catch (IOException ex) { System.out.println("Error in downloadFile: " + ex.getMessage()); } }
From source file:com.yenlo.synapse.transport.vfs.VFSUtils.java
/** * Acquires a file item lock before processing the item, guaranteing that the file is not * processed while it is being uploaded and/or the item is not processed by two listeners * * @param fsManager used to resolve the processing file * @param fo representing the processing file item * @return boolean true if the lock has been acquired or false if not */// ww w .j av a 2s. c o m public synchronized static boolean acquireLock(FileSystemManager fsManager, FileObject fo) { // generate a random lock value to ensure that there are no two parties // processing the same file Random random = new Random(); byte[] lockValue = String.valueOf(random.nextLong()).getBytes(); try { // check whether there is an existing lock for this item, if so it is assumed // to be processed by an another listener (downloading) or a sender (uploading) // lock file is derived by attaching the ".lock" second extension to the file name String fullPath = fo.getName().getURI(); int pos = fullPath.indexOf("?"); if (pos != -1) { fullPath = fullPath.substring(0, pos); } FileObject lockObject = fsManager.resolveFile(fullPath + ".lock"); if (lockObject.exists()) { log.debug("There seems to be an external lock, aborting the processing of the file " + fo.getName() + ". This could possibly be due to some other party already " + "processing this file or the file is still being uploaded"); } else { // write a lock file before starting of the processing, to ensure that the // item is not processed by any other parties lockObject.createFile(); OutputStream stream = lockObject.getContent().getOutputStream(); try { stream.write(lockValue); stream.flush(); stream.close(); } catch (IOException e) { lockObject.delete(); log.error("Couldn't create the lock file before processing the file " + fullPath, e); return false; } finally { lockObject.close(); } // check whether the lock is in place and is it me who holds the lock. This is // required because it is possible to write the lock file simultaneously by // two processing parties. It checks whether the lock file content is the same // as the written random lock value. // NOTE: this may not be optimal but is sub optimal FileObject verifyingLockObject = fsManager.resolveFile(fullPath + ".lock"); if (verifyingLockObject.exists() && verifyLock(lockValue, verifyingLockObject)) { return true; } } } catch (FileSystemException fse) { log.error("Cannot get the lock for the file : " + maskURLPassword(fo.getName().getURI()) + " before processing"); } return false; }
From source file:edu.uci.ics.hyracks.control.common.deployment.DeploymentUtils.java
/** * Download remote Http URLs and return the stored local file URLs * //from w w w . ja va2 s . c om * @param urls * the remote Http URLs * @param deploymentDir * the deployment jar storage directory * @param isNC * true is NC/false is CC * @return a list of local file URLs * @throws HyracksException */ private static List<URL> downloadURLs(List<URL> urls, String deploymentDir, boolean isNC) throws HyracksException { //retry 10 times at maximum for downloading binaries int retryCount = 10; int tried = 0; Exception trace = null; while (tried < retryCount) { try { tried++; List<URL> downloadedFileURLs = new ArrayList<URL>(); File dir = new File(deploymentDir); if (!dir.exists()) { FileUtils.forceMkdir(dir); } for (URL url : urls) { String urlString = url.toString(); int slashIndex = urlString.lastIndexOf('/'); String fileName = urlString.substring(slashIndex + 1).split("&")[1]; String filePath = deploymentDir + File.separator + fileName; File targetFile = new File(filePath); if (isNC) { HttpClient hc = HttpClientBuilder.create().build(); HttpGet get = new HttpGet(url.toString()); HttpResponse response = hc.execute(get); InputStream is = response.getEntity().getContent(); OutputStream os = new FileOutputStream(targetFile); try { IOUtils.copyLarge(is, os); } finally { os.close(); is.close(); } } downloadedFileURLs.add(targetFile.toURI().toURL()); } return downloadedFileURLs; } catch (Exception e) { e.printStackTrace(); trace = e; } } throw new HyracksException(trace); }
From source file:io.undertow.server.MaxRequestSizeTestCase.java
@BeforeClass public static void setup() { final BlockingHandler blockingHandler = new BlockingHandler(); DefaultServer.setRootHandler(blockingHandler); blockingHandler.setRootHandler(new HttpHandler() { @Override/*from ww w.ja v a2 s . co m*/ public void handleRequest(final HttpServerExchange exchange) throws Exception { final OutputStream outputStream = exchange.getOutputStream(); final InputStream inputStream = exchange.getInputStream(); String m = HttpClientUtils.readResponse(inputStream); Assert.assertEquals(A_MESSAGE, m); inputStream.close(); outputStream.close(); } }); }
From source file:ca.simplegames.micro.utils.IO.java
/** * Copy the contents of the given byte array to the given OutputStream. * Closes the stream when done.//from ww w. j av a 2 s .c o m * * @param in the byte array to copy from * @param out the OutputStream to copy to * @throws IOException in case of I/O errors */ public static void copy(byte[] in, OutputStream out) throws IOException { try { out.write(in); } finally { try { out.close(); } catch (IOException ex) { log.warn("Could not close OutputStream", ex); } } }