List of usage examples for java.io BufferedOutputStream close
@Override public void close() throws IOException
From source file:org.ametro.util.WebUtil.java
public static void downloadFileUnchecked(Object context, URI uri, File file, IDownloadListener listener) throws Exception { BufferedInputStream strm = null; if (listener != null) { listener.onBegin(context, file); }//from w w w . j a va 2 s .c om try { HttpClient client = ApplicationEx.getInstance().getHttpClient(); HttpGet request = new HttpGet(); request.setURI(uri); HttpResponse response = client.execute(request); StatusLine status = response.getStatusLine(); if (status.getStatusCode() == 200) { HttpEntity entity = response.getEntity(); long total = (int) entity.getContentLength(); long position = 0; if (file.exists()) { file.delete(); } BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(entity.getContent()); out = new BufferedOutputStream(new FileOutputStream(file)); byte[] bytes = new byte[2048]; for (int c = in.read(bytes); c != -1; c = in.read(bytes)) { out.write(bytes, 0, c); position += c; if (listener != null) { if (!listener.onUpdate(context, position, total)) { throw new DownloadCanceledException(); } } } } finally { if (in != null) { try { in.close(); } catch (Exception e) { } } if (out != null) { try { out.close(); } catch (Exception e) { } } } if (listener != null) { listener.onDone(context, file); } } else { String message = "Failed to download URL " + uri.toString() + " due error " + status.getStatusCode() + " " + status.getReasonPhrase(); throw new Exception(message); } } finally { if (strm != null) { try { strm.close(); } catch (IOException ex) { } } } }
From source file:io.wcm.maven.plugins.nodejs.installation.TarUnArchiver.java
/** * Unarchives the arvive into the pBaseDir * @param baseDir//from ww w . j a v a 2 s . c o m * @throws MojoExecutionException */ public void unarchive(String baseDir) throws MojoExecutionException { try { FileInputStream fis = new FileInputStream(archive); // TarArchiveInputStream can be constructed with a normal FileInputStream if // we ever need to extract regular '.tar' files. final TarArchiveInputStream tarIn = new TarArchiveInputStream(new GzipCompressorInputStream(fis)); TarArchiveEntry tarEntry = tarIn.getNextTarEntry(); while (tarEntry != null) { // Create a file for this tarEntry final File destPath = new File(baseDir + File.separator + tarEntry.getName()); if (tarEntry.isDirectory()) { destPath.mkdirs(); } else { destPath.createNewFile(); destPath.setExecutable(true); //byte [] btoRead = new byte[(int)tarEntry.getSize()]; byte[] btoRead = new byte[8024]; final BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(destPath)); int len = 0; while ((len = tarIn.read(btoRead)) != -1) { bout.write(btoRead, 0, len); } bout.close(); } tarEntry = tarIn.getNextTarEntry(); } tarIn.close(); } catch (IOException e) { throw new MojoExecutionException("Could not extract archive: '" + archive.getAbsolutePath() + "'", e); } }
From source file:com.honnix.cheater.bundle.CheaterActivator.java
private void setTrustStore(BundleContext context) throws IOException { InputStream is = context.getBundle().getEntry("/etc/jssecacerts").openStream(); BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(TEMP_TRUST_STORE)); byte[] buffer = new byte[255]; int length;/*from ww w . j a va2 s . c om*/ while ((length = is.read(buffer)) != -1) { os.write(buffer, 0, length); } os.flush(); os.close(); is.close(); System.setProperty(CheaterConstant.TRUST_STORE_KEY, TEMP_TRUST_STORE); }
From source file:com.wipro.ats.bdre.md.rest.TDUploaderAPI.java
@RequestMapping(value = "/uploadtr/{processIdValue}", method = RequestMethod.POST) @ResponseBody// w w w . j a va 2s.c o m public RestWrapper uploadInTeradata(@PathVariable("processIdValue") Integer processIdValue, @RequestParam("file") MultipartFile file, Principal principal) { if (!file.isEmpty()) { try { String uploadedFilesDirectory = MDConfig.getProperty(UPLOADBASEDIRECTORY); String name = file.getOriginalFilename(); byte[] bytes = file.getBytes(); String monitorPath = null; LOGGER.info("processIDvalue is " + processIdValue); com.wipro.ats.bdre.md.dao.jpa.Process process = processDAO.get(processIdValue); LOGGER.info("Process fetched = " + process.getProcessId()); List<Properties> propertiesList = propertiesDAO.getByProcessId(process); LOGGER.info("No.of Properties fetched= " + propertiesList.size()); for (Properties property : propertiesList) { LOGGER.debug( "property fetched is " + property.getId().getPropKey() + " " + property.getPropValue()); if ("monitored-dir-name".equals(property.getId().getPropKey())) { monitorPath = property.getPropValue(); } } String uploadLocation = monitorPath; LOGGER.info("Upload location: " + uploadLocation); File fileDir = new File(uploadLocation); fileDir.mkdirs(); File fileToBeSaved = new File(uploadLocation + "/" + name); BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(fileToBeSaved)); stream.write(bytes); stream.close(); LOGGER.debug("Uploaded file: " + fileToBeSaved); //Populating Uploaded file bean to return in RestWrapper UploadedFile uploadedFile = new UploadedFile(); uploadedFile.setParentProcessId(processIdValue); // uploadedFile.setSubDir(subDir); uploadedFile.setFileName(name); uploadedFile.setFileSize(fileToBeSaved.length()); LOGGER.debug("The UploadedFile bean:" + uploadedFile); LOGGER.info("File uploaded : " + uploadedFile + " uploaded by User:" + principal.getName()); return new RestWrapper(uploadedFile, RestWrapper.OK); } catch (Exception e) { LOGGER.error(e); return new RestWrapper(e.getMessage(), RestWrapper.ERROR); } } else { return new RestWrapper("You failed to upload because the file was empty.", RestWrapper.ERROR); } }
From source file:net.solarnetwork.node.backup.ZipStreamBackupResource.java
@Override public InputStream getInputStream() throws IOException { // to support calling getInputStream() more than once, tee the input to a temp file // the first time, and subsequent times if (tempFile != null) { return new BufferedInputStream(new FileInputStream(tempFile)); }/*from w w w. ja v a 2s. c o m*/ tempFile = File.createTempFile(entry.getName(), ".tmp"); final BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile)); return new TeeInputStream(new FilterInputStream(stream) { @Override public void close() throws IOException { out.flush(); out.close(); } }, out, false); }
From source file:fi.mikuz.boarder.gui.ZipImporter.java
private void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException { File outputFile = new File(outputDir, entry.getName()); if (entry.isDirectory()) { createDir(outputFile);/* w w w. ja v a 2 s.c o m*/ return; } if (!outputFile.getParentFile().exists()) { createDir(outputFile.getParentFile()); } log = "Extracting: " + entry.getName() + "\n" + log; postMessage("Please wait\n\n" + log); Log.d(TAG, "Extracting: " + entry); BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry)); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); try { IOUtils.copy(inputStream, outputStream); } finally { outputStream.close(); inputStream.close(); } }
From source file:com.galois.qrstream.lib.DecodeThread.java
private @NotNull File storeData(Job message) throws IOException { File cacheDir = context.getCacheDir(); File tmpFile = File.createTempFile(Constants.APP_TAG, "", cacheDir); // make tmpFile world-readable: tmpFile.setReadable(true, false);//w w w. ja v a 2 s .c o m tmpFile.deleteOnExit(); BufferedOutputStream bos = null; try { bos = new BufferedOutputStream(new FileOutputStream(tmpFile)); bos.write(message.getData()); bos.flush(); } finally { if (null != bos) { bos.close(); } } return tmpFile; }
From source file:edu.ur.util.FileUtil.java
/** * Create a file in the specified directory with the * specified name and place in it the specified contents. * * @param directory - directory in which to create the file * @param fileName - name of the file to create * @param contents - Simple string to create the file *//*from ww w.j av a2 s . c o m*/ public File creatFile(File directory, String fileName, String contents) { File f = new File(directory.getAbsolutePath() + IOUtils.DIR_SEPARATOR + fileName); // create the file BufferedOutputStream bos = null; FileOutputStream fos = null; try { f.createNewFile(); fos = new FileOutputStream(f); bos = new BufferedOutputStream(fos); bos.write(contents.getBytes()); bos.flush(); bos.close(); fos.close(); } catch (Exception e) { if (bos != null) { try { bos.close(); } catch (Exception ec) { } } if (fos != null) { try { fos.close(); } catch (Exception ec) { } } throw new RuntimeException(e); } return f; }
From source file:com.wabacus.system.dataimport.DataImportItem.java
public static void backupOrDeleteDataFile(File fileObj) { try {/* w w w . j a va2 s.co m*/ if (fileObj == null || !fileObj.exists()) { return; } String backuppath = Config.getInstance().getSystemConfigValue("dataimport-backuppath", ""); if (backuppath.equals("")) { log.debug("?" + fileObj.getAbsolutePath()); } else {//? String filename = fileObj.getName(); int idxdot = filename.lastIndexOf("."); if (idxdot > 0) { filename = filename.substring(0, idxdot) + "_" + Tools.getStrDatetime("yyyyMMddHHmmss", new Date()) + filename.substring(idxdot); } else { filename = filename + "_" + Tools.getStrDatetime("yyyyMMddHHmmss", new Date()); } File destFile = new File( FilePathAssistant.getInstance().standardFilePath(backuppath + File.separator + filename)); log.debug("?" + fileObj.getAbsolutePath() + "" + backuppath + ""); BufferedInputStream bis = null; BufferedOutputStream bos = null; try { bis = new BufferedInputStream(new FileInputStream(fileObj)); bos = new BufferedOutputStream(new FileOutputStream(destFile)); byte[] btmp = new byte[1024]; while (bis.read(btmp) != -1) { bos.write(btmp); } } catch (Exception e) { log.error("?" + fileObj.getAbsolutePath() + "", e); } finally { try { if (bis != null) bis.close(); } catch (IOException e) { e.printStackTrace(); } try { if (bos != null) bos.close(); } catch (IOException e) { e.printStackTrace(); } } } fileObj.delete(); } catch (Exception e) { log.error("?" + fileObj.getAbsolutePath() + "", e); } }
From source file:org.iti.agrimarket.administration.view.AddCategoryController.java
/** * Amr upload image and form data/* w w w .j ava2s . c om*/ * */ @RequestMapping(method = RequestMethod.POST, value = "/admin/addcategory") public String addCategory(@RequestParam("nameAr") String nameAr, @RequestParam("nameEn") String nameEn, @RequestParam("parentCategoryId") int parentCategoryId, @RequestParam("file") MultipartFile file) { System.out.println("save user func ---------"); System.out.println("full Name :" + nameAr); Category category = new Category(); category.setNameAr(nameAr); category.setNameEn(nameEn); Category parentCategory = categoryService.getCategory(parentCategoryId); category.setCategory(parentCategory); category.setSoundUrl("/to be continue"); int res = categoryService.addCategory(category); if (!file.isEmpty()) { String fileName = category.getId() + String.valueOf(new Date().getTime()); try { System.out.println("fileName :" + fileName); byte[] bytes = file.getBytes(); MagicMatch match = Magic.getMagicMatch(bytes); final String ext = "." + match.getExtension(); File parentDir = new File(Constants.IMAGE_PATH + Constants.CATEGORY_PATH); if (!parentDir.isDirectory()) { parentDir.mkdirs(); } BufferedOutputStream stream = new BufferedOutputStream( new FileOutputStream(new File(Constants.IMAGE_PATH + Constants.CATEGORY_PATH + fileName))); stream.write(bytes); stream.close(); category.setImageUrl(Constants.IMAGE_PRE_URL + Constants.CATEGORY_PATH + fileName + ext); categoryService.updateCategory(category); } catch (Exception e) { // logger.error(e.getMessage()); categoryService.deleteCategory(category.getId()); // delete the category if something goes wrong return "redirect:/admin/categories_page.htm"; } } else { category.setImageUrl(Constants.IMAGE_PRE_URL + Constants.CATEGORY_PATH + "default_category.jpg"); categoryService.updateCategory(category); } return "redirect:/admin/categories_page.htm"; }