List of usage examples for java.io BufferedInputStream close
public void close() throws IOException
From source file:ZipUtilTest.java
public void testUnpackEntryFromStreamToFile() throws IOException { final String name = "foo"; final byte[] contents = "bar".getBytes(); File file = File.createTempFile("temp", null); try {// w ww. j a v a2 s . co m // Create the ZIP file ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file)); try { zos.putNextEntry(new ZipEntry(name)); zos.write(contents); zos.closeEntry(); } finally { IOUtils.closeQuietly(zos); } FileInputStream fis = new FileInputStream(file); File outputFile = File.createTempFile("temp-output", null); boolean result = ZipUtil.unpackEntry(fis, name, outputFile); assertTrue(result); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(outputFile)); byte[] actual = new byte[1024]; int read = bis.read(actual); bis.close(); assertEquals(new String(contents), new String(actual, 0, read)); } finally { FileUtils.deleteQuietly(file); } }
From source file:ispyb.client.common.util.FileUtil.java
/** * Gunzip a local file/*from www. j a v a 2s . c o m*/ * * @param sourceFileName * @return */ public static byte[] readBytes(String sourceFileName) { ByteArrayOutputStream outBuffer = null; FileInputStream inFile = null; BufferedInputStream bufInputStream = null; try { outBuffer = new ByteArrayOutputStream(); inFile = new FileInputStream(sourceFileName); bufInputStream = new BufferedInputStream(inFile); byte[] tmpBuffer = new byte[8 * 1024]; int n = 0; while ((n = bufInputStream.read(tmpBuffer)) >= 0) outBuffer.write(tmpBuffer, 0, n); } catch (FileNotFoundException fnf) { LOG.error("[readBytes] File not found :" + fnf.getMessage()); } catch (Exception e) { e.printStackTrace(); } finally { if (inFile != null) { try { inFile.close(); } catch (IOException ioex) { // ignore } } if (outBuffer != null) { try { outBuffer.close(); } catch (IOException ioex) { // ignore } } if (bufInputStream != null) { try { bufInputStream.close(); } catch (IOException ioex) { // ignore } } } return outBuffer.toByteArray(); }
From source file:com.kaylerrenslow.armaDialogCreator.updater.tasks.AdcVersionCheckTask.java
private void downloadLatestRelease(String downloadUrl) throws Exception { setIndeterminateProgress();//from www. j a va 2 s . c o m setStatusText("Updater.downloading_newest_version"); URL url = new URL(downloadUrl); BufferedInputStream in = null; FileOutputStream fout = null; URLConnection urlConnection = null; long workDone = 0; downloadDirectory.mkdirs(); try { urlConnection = url.openConnection(); in = new BufferedInputStream(urlConnection.getInputStream()); fout = new FileOutputStream(downloadDirectory.getAbsolutePath() + "/" + adcJarSave.getName()); long downloadSize = urlConnection.getContentLengthLong(); if (downloadDirectory.getFreeSpace() < downloadSize) { in.close(); fout.close(); urlConnection.getInputStream().close(); throw new NotEnoughFreeSpaceException(ADCUpdater.bundle.getString("Updater.not_enough_free_space")); } final byte data[] = new byte[1024]; int count; while ((count = in.read(data, 0, 1024)) != -1) { fout.write(data, 0, count); workDone += count; updateProgress(workDone, downloadSize); } } finally { if (in != null) { in.close(); } if (urlConnection != null) { urlConnection.getInputStream().close(); } if (fout != null) { fout.close(); } } setStatusText("Updater.download_complete"); Thread.sleep(1000); setStatusText("Updater.launching"); Thread.sleep(1000); }
From source file:org.jboss.ejb3.packagemanager.retriever.impl.HttpPackageRetriever.java
/** * @see org.jboss.ejb3.packagemanager.retriever.PackageRetriever#retrievePackage(PackageManagerContext, URL) *///from w w w . ja v a 2 s. c o m @Override public File retrievePackage(PackageManagerContext pkgMgrCtx, URL packagePath) throws PackageRetrievalException { if (!packagePath.getProtocol().equals("http")) { throw new PackageRetrievalException("Cannot handle " + packagePath); } HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(packagePath.toExternalForm()); HttpResponse httpResponse = null; try { httpResponse = httpClient.execute(httpGet); } catch (Exception e) { throw new PackageRetrievalException("Exception while retrieving package " + packagePath, e); } if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new PackageRetrievalException("Http retrieval wasn't successful, returned status code " + httpResponse.getStatusLine().getStatusCode()); } HttpEntity httpEntity = httpResponse.getEntity(); try { // TODO: should this tmp be deleted on exit? File tmpPkgFile = File.createTempFile("tmp", ".jar", pkgMgrCtx.getPackageManagerEnvironment().getPackageManagerTmpDir()); FileOutputStream fos = new FileOutputStream(tmpPkgFile); BufferedOutputStream bos = null; BufferedInputStream bis = null; try { bos = new BufferedOutputStream(fos); InputStream is = httpEntity.getContent(); bis = new BufferedInputStream(is); byte[] content = new byte[4096]; int length; while ((length = bis.read(content)) != -1) { bos.write(content, 0, length); } bos.flush(); } finally { if (bos != null) { bos.close(); } if (bis != null) { bis.close(); } } return tmpPkgFile; } catch (IOException ioe) { throw new PackageRetrievalException("Could not process the retrieved package", ioe); } // TODO: I need to read the HttpClient 4.x javadocs to figure out the API for closing the // Http connection }
From source file:JarMaker.java
/** * Unpack the jar file to a directory, till teaf files * @param file The source file name/*from w ww . j a v a 2s.co m*/ * @param file1 The target directory * @author wangxp * @version 2003/11/07 */ public static void unpackAppJar(String file, String file1) throws IOException { // m_log.debug("unpackAppJar begin. file="+file+"|||file1="+file1); BufferedInputStream bufferedinputstream = new BufferedInputStream(new FileInputStream(file)); ZipInputStream zipinputstream = new ZipInputStream(bufferedinputstream); byte abyte0[] = new byte[1024]; for (ZipEntry zipentry = zipinputstream.getNextEntry(); zipentry != null; zipentry = zipinputstream .getNextEntry()) { File file2 = new File(file1, zipentry.getName()); if (zipentry.isDirectory()) { if (!file2.exists() && !file2.mkdirs()) throw new IOException("Could not make directory " + file2.getPath()); } else { File file3 = file2.getParentFile(); if (file3 != null && !file3.exists() && !file3.mkdirs()) throw new IOException("Could not make directory " + file3.getPath()); BufferedOutputStream bufferedoutputstream = new BufferedOutputStream(new FileOutputStream(file2)); int i; try { while ((i = zipinputstream.read(abyte0, 0, abyte0.length)) != -1) bufferedoutputstream.write(abyte0, 0, i); } catch (IOException ie) { ie.printStackTrace(); // m_logger.error(ie); throw ie; } bufferedoutputstream.close(); } } zipinputstream.close(); bufferedinputstream.close(); // m_log.debug("unpackAppJar end."); }
From source file:com.microsoft.tfs.client.common.ui.teambuild.commands.CreateUploadZipCommand.java
/** * Copy zip file and remove ignored files * * @param srcFile/*from ww w . ja v a2 s.c o m*/ * @param destFile * @throws IOException */ public void copyZip(final String srcFile, final String destFile) throws Exception { loadDefaultExcludePattern(getRootFolderInZip(srcFile)); final ZipFile zipSrc = new ZipFile(srcFile); final ZipOutputStream out = new ZipOutputStream(new FileOutputStream(destFile)); try { final Enumeration<? extends ZipEntry> entries = zipSrc.entries(); while (entries.hasMoreElements()) { final ZipEntry entry = entries.nextElement(); if (!isExcluded(LocalPath.combine(srcFile, entry.getName()), false, srcFile)) { final ZipEntry newEntry = new ZipEntry(entry.getName()); out.putNextEntry(newEntry); final BufferedInputStream in = new BufferedInputStream(zipSrc.getInputStream(entry)); int len; final byte[] buf = new byte[65536]; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } out.closeEntry(); in.close(); } } out.finish(); } catch (final IOException e) { errorMsg = Messages.getString("CreateUploadZipCommand.CopyArchiveErrorMessageFormat"); //$NON-NLS-1$ log.error("Exceptions when copying exising archive ", e); //$NON-NLS-1$ throw e; } finally { out.close(); zipSrc.close(); } }
From source file:edu.stanford.epadd.launcher.Main.java
public static void copy_stream_to_file(InputStream is, String filename) throws IOException { int bufsize = 64 * 1024; BufferedInputStream bis = null; BufferedOutputStream bos = null; try {/*from w w w . j a va 2s. c o m*/ File f = new File(filename); if (f.exists()) { // out.println ("File " + filename + " exists"); boolean b = f.delete(); // best effort to delete file if it exists. this is because windows often complains about perms if (!b) out.println("Warning: failed to delete " + filename); } bis = new BufferedInputStream(is, bufsize); bos = new BufferedOutputStream(new FileOutputStream(filename), bufsize); byte buf[] = new byte[bufsize]; while (true) { int n = bis.read(buf); if (n <= 0) break; bos.write(buf, 0, n); } } catch (IOException ioe) { out.println("ERROR trying to copy data to file: " + filename + ", forging ahead nevertheless"); } finally { if (bis != null) bis.close(); if (bos != null) bos.close(); } }
From source file:com.taurus.compratae.appservice.impl.EnvioArchivoFTPServiceImpl.java
public void conectarFTP(Archivo archivo) { FTPClient client = new FTPClient(); /*String sFTP = "127.0.0.1"; String sUser = "tae";/* w w w.j a va2 s . c o m*/ String sPassword = "tae";*/ String sFTP = buscarParametros(FTP_SERVER); String sUser = buscarParametros(FTP_USER); String sPassword = buscarParametros(FTP_PASSWORD); /////////////////////////////////// //String[] lista; try { client.connect(sFTP); boolean login = client.login(sUser, sPassword); System.out.println("1. Directorio de trabajo: " + client.printWorkingDirectory()); client.setFileType(FTP.BINARY_FILE_TYPE); BufferedInputStream buffIn = null; buffIn = new BufferedInputStream(new FileInputStream(archivo.getNombre())); client.enterLocalPassiveMode(); StringTokenizer tokens = new StringTokenizer(archivo.getNombre(), "/");//Para separar el nombre de la ruta. int i = 0; String nombre = ""; while (tokens.hasMoreTokens()) { if (i == 1) { nombre = tokens.nextToken(); i++; } else { i++; } } client.storeFile(nombre, buffIn); buffIn.close(); /*lista = client.listNames(); for (String lista1 : lista) { System.out.println(lista1); }*/ //client.changeWorkingDirectory("\\done"); //System.out.println("2. Working Directory: " + client.printWorkingDirectory()); client.logout(); client.disconnect(); System.out.println("Termin de conectarme al FTP!!"); } catch (IOException ioe) { ioe.printStackTrace(); } }
From source file:com.microsoft.tfs.core.clients.versioncontrol.localworkspace.LocalMetadataTable.java
public LocalMetadataTable(final String filename, final LocalMetadataTable cachedLoadSource, final int retryCount) throws IOException { Check.notNull(filename, "filename"); //$NON-NLS-1$ this.filename = filename; setDirty(false);/* ww w. j a v a2 s. com*/ setAborted(false); try { tableLock = new LocalMetadataTableLock(filename, retryCount, false); recover(); initialize(); log.debug(MessageFormat.format("Loading {0}", this.getClass().getCanonicalName())); //$NON-NLS-1$ final long start = System.currentTimeMillis(); if (!tryCachedLoad(cachedLoadSource)) { FileInputStream is = null; BufferedInputStream bis = null; try { is = getInputStream(); if (is != null) { bis = new BufferedInputStream(is); load(bis); } } finally { if (bis != null) { bis.close(); } if (is != null) { is.close(); } } } log.debug(MessageFormat.format("Total time for load of {0} was {1} ms", //$NON-NLS-1$ this.getClass().getName(), (System.currentTimeMillis() - start))); } catch (final Exception e) { close(false); throw new VersionControlException(e); } }
From source file:ebay.dts.client.FileTransferActions.java
public void downloadFile2(String fileName, String jobId, String fileReferenceId) throws EbayConnectorException { String callName = "downloadFile"; try {// ww w.j ava 2 s. c o m FileTransferServicePort port = call.setFTSMessageContext(callName); com.ebay.marketplace.services.DownloadFileRequest request = new com.ebay.marketplace.services.DownloadFileRequest(); request.setFileReferenceId(fileReferenceId); request.setTaskReferenceId(jobId); DownloadFileResponse response = port.downloadFile(request); if (response.getAck().equals(AckValue.SUCCESS)) { logger.debug(AckValue.SUCCESS.toString()); } else { logger.error(response.getErrorMessage().getError().get(0).getMessage()); throw new EbayConnectorException(response.getErrorMessage().getError().get(0).getMessage()); } FileAttachment attachment = response.getFileAttachment(); DataHandler dh = attachment.getData(); try { InputStream in = dh.getInputStream(); BufferedInputStream bis = new BufferedInputStream(new GZIPInputStream(in)); FileOutputStream fo = new FileOutputStream(new File(fileName)); // "C:/myDownLoadFile.gz" BufferedOutputStream bos = new BufferedOutputStream(fo); int bytes_read = 0; byte[] dataBuf = new byte[4096]; while ((bytes_read = bis.read(dataBuf)) != -1) { bos.write(dataBuf, 0, bytes_read); } bis.close(); bos.flush(); bos.close(); logger.info("File attachment has been saved successfully to " + fileName); } catch (IOException e) { logger.error("Exception caught while trying to save the attachement"); throw new EbayConnectorException("Exception caught while trying to save the attachement", e); } } catch (Exception e) { throw new EbayConnectorException("Exception caught while trying to save the attachement", e); } }