List of usage examples for java.io BufferedInputStream close
public void close() throws IOException
From source file:com.zrlh.llkc.funciton.Http_Utility.java
/** * Upload image into output stream ./*from w ww . j a v a 2 s. c o m*/ * * @param out * output stream for uploading bitmap * @param imgBm * @param keyId * keyId * @param type * * @throws Exception */ private static void imageContentToUpload(OutputStream out, Bitmap imgBm) throws Exception { StringBuilder temp = new StringBuilder(); temp.append(MP_BOUNDARY).append("\r\n"); temp.append("Content-Disposition: form-data; name=\"pic\"; filename=\"").append("news_image") .append("\"\r\n"); String filetype = "image/png"; temp.append("Content-Type: ").append(filetype).append("\r\n\r\n"); byte[] res = temp.toString().getBytes(); BufferedInputStream bis = null; try { out.write(res); imgBm.compress(CompressFormat.PNG, 75, out); out.write("\r\n".getBytes()); out.write(("\r\n" + END_MP_BOUNDARY).getBytes()); } catch (IOException e) { throw new Exception(e); } finally { if (null != bis) { try { bis.close(); } catch (IOException e) { throw new Exception(e); } } } }
From source file:com.glaf.core.util.ZipUtils.java
public static byte[] getZipBytes(Map<String, InputStream> dataMap) { byte[] bytes = null; try {/*w ww . ja va 2 s . c o m*/ ByteArrayOutputStream baos = new ByteArrayOutputStream(); BufferedOutputStream bos = new BufferedOutputStream(baos); JarOutputStream jos = new JarOutputStream(bos); if (dataMap != null) { Set<Entry<String, InputStream>> entrySet = dataMap.entrySet(); for (Entry<String, InputStream> entry : entrySet) { String name = entry.getKey(); InputStream inputStream = entry.getValue(); if (name != null && inputStream != null) { BufferedInputStream bis = new BufferedInputStream(inputStream); JarEntry jarEntry = new JarEntry(name); jos.putNextEntry(jarEntry); while ((len = bis.read(buf)) >= 0) { jos.write(buf, 0, len); } bis.close(); jos.closeEntry(); } } } jos.flush(); jos.close(); bos.flush(); bos.close(); bytes = baos.toByteArray(); baos.close(); return bytes; } catch (Exception ex) { throw new RuntimeException(ex); } }
From source file:com.aurel.track.util.emailHandling.MailReader.java
/** * Saves attachment//from w w w. j a va2s .co m */ public static File saveFile(String filename, InputStream input) throws IOException { // in case there is no filename, create temporary file and use its // filename instead String tempDir = HandleHome.getTrackplus_Home() + File.separator + HandleHome.DATA_DIR + File.separator + "temp"; File dirTem = new File(tempDir); if (!dirTem.exists()) { dirTem.mkdirs(); } File file; if (filename == null) { file = File.createTempFile("xxxxxx", ".out", dirTem); } else { // Existing files will not be overwritten file = new File(dirTem, filename); } int i = 0; while (file.exists()) { // Extend filename by number so it is unique file = new File(dirTem, i + filename); i++; } // BufferedOutputStream for writing into the file BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file)); // BufferedInputStream for reading the parts BufferedInputStream bis = new BufferedInputStream(input); // read data and write to output stream int aByte; while ((aByte = bis.read()) != -1) { bos.write(aByte); } // release resources bos.flush(); bos.close(); bis.close(); return file; }
From source file:net.amigocraft.mpt.util.MiscUtil.java
public static boolean unzip(ZipFile zip, File dest, List<String> files) throws MPTException { boolean returnValue = true; try {/*from www.ja va 2 s .co m*/ List<String> existingDirs = new ArrayList<>(); Enumeration<? extends ZipEntry> en = zip.entries(); entryLoop: while (en.hasMoreElements()) { ZipEntry entry = en.nextElement(); String name = entry.getName().startsWith("./") ? entry.getName().substring(2, entry.getName().length()) : entry.getName(); File file = new File(dest, name); if (entry.isDirectory()) { if (file.exists()) { if (DISALLOW_MERGE) { existingDirs.add(name); if (VERBOSE) Main.log.warning("Refusing to extract directory " + name + ": already exists"); } } } else { files.add(name); for (String dir : DISALLOWED_DIRECTORIES) { if (file.getPath().startsWith(dir)) { if (VERBOSE) Main.log.warning("Refusing to extract " + name + " from " + zip.getName() + ": parent directory \"" + dir + "\" is not allowed"); continue entryLoop; } } if (DISALLOW_MERGE) { for (String dir : existingDirs) { if (file.getPath().substring(2, file.getPath().length()).replace(File.separator, "/") .startsWith(dir)) { continue entryLoop; } } } if (!DISALLOW_OVERWRITE || !file.exists()) { file.getParentFile().mkdirs(); for (String ext : DISALLOWED_EXTENSIONS) { if (file.getName().endsWith(ext)) { if (VERBOSE) Main.log.warning("Refusing to extract " + name + " from " + zip.getName() + ": extension \"" + ext + "\" is not allowed"); returnValue = false; continue entryLoop; } } BufferedInputStream bIs = new BufferedInputStream(zip.getInputStream(entry)); int b; byte[] buffer = new byte[1024]; FileOutputStream fOs = new FileOutputStream(file); BufferedOutputStream bOs = new BufferedOutputStream(fOs, 1024); while ((b = bIs.read(buffer, 0, 1024)) != -1) bOs.write(buffer, 0, b); bOs.flush(); bOs.close(); bIs.close(); } else { if (VERBOSE) Main.log.warning( "Refusing to extract " + name + " from " + zip.getName() + ": already exists"); returnValue = false; } } } } catch (Exception ex) { ex.printStackTrace(); //TODO throw new MPTException(ERROR_COLOR + "Failed to extract archive!"); } return returnValue; }
From source file:abfab3d.io.input.ModelLoader.java
private static void unzipEntry(ZipFile zipFile, ZipArchiveEntry entry, File dest) throws IOException { if (entry.isDirectory()) { createDir(new File(dest, entry.getName())); return;// www .j ava2 s . com } File outputFile = new File(dest, entry.getName()); if (!outputFile.getParentFile().exists()) { createDir(outputFile.getParentFile()); } BufferedInputStream inputStream = new BufferedInputStream(zipFile.getInputStream(entry)); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); try { IOUtils.copy(inputStream, outputStream); } finally { if (outputStream != null) outputStream.close(); if (inputStream != null) inputStream.close(); } }
From source file:Main.java
/** * Zips a subfolder//from w w w . ja v a 2s .com */ protected static void zipSubFolder(ZipOutputStream zipOut, File srcFolder, int basePathLength) throws IOException { final int BUFFER = 2048; File[] fileList = srcFolder.listFiles(); BufferedInputStream bis = null; for (File file : fileList) { if (file.isDirectory()) { zipSubFolder(zipOut, file, basePathLength); } else { byte data[] = new byte[BUFFER]; String unmodifiedFilePath = file.getPath(); String relativePath = unmodifiedFilePath.substring(basePathLength); Log.d("ZIP SUBFOLDER", "Relative Path : " + relativePath); FileInputStream fis = new FileInputStream(unmodifiedFilePath); bis = new BufferedInputStream(fis, BUFFER); ZipEntry zipEntry = new ZipEntry(relativePath); zipOut.putNextEntry(zipEntry); int count; while ((count = bis.read(data, 0, BUFFER)) != -1) { zipOut.write(data, 0, count); } bis.close(); } } }
From source file:net.servicestack.client.Utils.java
public static byte[] readBytesToEnd(InputStream stream) throws IOException { ByteArrayBuffer bytes = new ByteArrayBuffer(1024); final BufferedInputStream bufferedStream = new BufferedInputStream(stream, 8192); try {//from ww w .j av a 2s. c o m final byte[] buffer = new byte[1024]; int bytesRead = 0; while ((bytesRead = bufferedStream.read(buffer)) > 0) { bytes.append(buffer, 0, bytesRead); } return bytes.toByteArray(); } finally { bufferedStream.close(); } }
From source file:jeeves.xlink.Processor.java
/** * Resolves an xlink/* w w w. j a v a 2s. c om*/ */ public static synchronized Element resolveXLink(String uri, String idSearch, ServiceContext srvContext) throws IOException, JDOMException, CacheException { cleanFailures(); if (failures.size() > MAX_FAILURES) { throw new RuntimeException("There have been " + failures.size() + " timeouts resolving xlinks in the last " + ELAPSE_TIME + " ms"); } Element remoteFragment = null; try { // TODO-API: Support local protocol on /api/registries/ if (uri.startsWith(XLink.LOCAL_PROTOCOL)) { SpringLocalServiceInvoker springLocalServiceInvoker = srvContext .getBean(SpringLocalServiceInvoker.class); remoteFragment = (Element) springLocalServiceInvoker.invoke(uri); } else { // Avoid references to filesystem if (uri.toLowerCase().startsWith("file://")) { return null; } uri = uri.replaceAll("&+", "&"); String mappedURI = mapURI(uri); JeevesJCS xlinkCache = JeevesJCS.getInstance(XLINK_JCS); remoteFragment = (Element) xlinkCache.getFromGroup(uri.toLowerCase(), mappedURI); if (remoteFragment == null) { Log.info(Log.XLINK_PROCESSOR, "cache MISS on " + uri.toLowerCase()); URL url = new URL(uri.replaceAll("&", "&")); URLConnection conn = url.openConnection(); conn.setConnectTimeout(1000); BufferedInputStream in = new BufferedInputStream(conn.getInputStream()); try { remoteFragment = Xml.loadStream(in); if (Log.isDebugEnabled(Log.XLINK_PROCESSOR)) Log.debug(Log.XLINK_PROCESSOR, "Read:\n" + Xml.getString(remoteFragment)); } finally { in.close(); } } else { Log.debug(Log.XLINK_PROCESSOR, "cache HIT on " + uri.toLowerCase()); } if (remoteFragment != null && !remoteFragment.getName().equalsIgnoreCase("error")) { xlinkCache.putInGroup(uri.toLowerCase(), mappedURI, remoteFragment); if (Log.isDebugEnabled(Log.XLINK_PROCESSOR)) Log.debug(Log.XLINK_PROCESSOR, "cache miss for " + uri); } else { return null; } } } catch (Exception e) { // MalformedURLException, IOException synchronized (Processor.class) { failures.add(System.currentTimeMillis()); } Log.error(Log.XLINK_PROCESSOR, "Failed on " + uri, e); } // search for and return only the xml fragment that has @id=idSearch Element res = null; if (idSearch != null) { String xpath = "*//*[@id='" + idSearch + "']"; try { res = Xml.selectElement(remoteFragment, xpath); if (res != null) { res = (Element) res.clone(); res.removeAttribute("id"); } } catch (Exception e) { Log.warning(Log.XLINK_PROCESSOR, "Failed to search for remote fragment using " + xpath + ", error" + e.getMessage()); return null; } } else { if (remoteFragment == null) { return null; } else { res = (Element) remoteFragment.clone(); } } if (Log.isDebugEnabled(Log.XLINK_PROCESSOR)) Log.debug(Log.XLINK_PROCESSOR, "Read:" + Xml.getString(res)); return res; }
From source file:Main.java
public static void unzip(String strZipFile) { try {/*from w w w.j a va2s. co m*/ /* * STEP 1 : Create directory with the name of the zip file * * For e.g. if we are going to extract c:/demo.zip create c:/demo directory where we can extract all the zip entries */ File fSourceZip = new File(strZipFile); String zipPath = strZipFile.substring(0, strZipFile.length() - 4); File temp = new File(zipPath); temp.mkdir(); System.out.println(zipPath + " created"); /* * STEP 2 : Extract entries while creating required sub-directories */ ZipFile zipFile = new ZipFile(fSourceZip); Enumeration<? extends ZipEntry> e = zipFile.entries(); while (e.hasMoreElements()) { ZipEntry entry = (ZipEntry) e.nextElement(); File destinationFilePath = new File(zipPath, entry.getName()); // create directories if required. destinationFilePath.getParentFile().mkdirs(); // if the entry is directory, leave it. Otherwise extract it. if (entry.isDirectory()) { continue; } else { // System.out.println("Extracting " + destinationFilePath); /* * Get the InputStream for current entry of the zip file using * * InputStream getInputStream(Entry entry) method. */ BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); int b; byte buffer[] = new byte[1024]; /* * read the current entry from the zip file, extract it and write the extracted file. */ FileOutputStream fos = new FileOutputStream(destinationFilePath); BufferedOutputStream bos = new BufferedOutputStream(fos, 1024); while ((b = bis.read(buffer, 0, 1024)) != -1) { bos.write(buffer, 0, b); } // flush the output stream and close it. bos.flush(); bos.close(); // close the input stream. bis.close(); } } zipFile.close(); } catch (IOException ioe) { System.out.println("IOError :" + ioe); } }
From source file:Main.java
public static void downloadImage(String imageUrl) { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { Log.d("TAG", "monted sdcard"); } else {//from ww w .j a v a 2 s. co m Log.d("TAG", "has no sdcard"); } HttpURLConnection con = null; FileOutputStream fos = null; BufferedOutputStream bos = null; BufferedInputStream bis = null; File imageFile = null; try { URL url = new URL(imageUrl); con = (HttpURLConnection) url.openConnection(); con.setConnectTimeout(5 * 1000); con.setReadTimeout(15 * 1000); con.setDoInput(true); con.setDoOutput(true); bis = new BufferedInputStream(con.getInputStream()); imageFile = new File(getImagePath(imageUrl)); fos = new FileOutputStream(imageFile); bos = new BufferedOutputStream(fos); byte[] b = new byte[1024]; int length; while ((length = bis.read(b)) != -1) { bos.write(b, 0, length); bos.flush(); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (bis != null) { bis.close(); } if (bos != null) { bos.close(); } if (con != null) { con.disconnect(); } } catch (IOException e) { e.printStackTrace(); } } if (imageFile != null) { } }