List of usage examples for java.io BufferedInputStream close
public void close() throws IOException
From source file:Main.java
public static boolean downloadUrlToStream(String urlString, OutputStream outputStream) { HttpURLConnection urlConnection = null; BufferedOutputStream out = null; BufferedInputStream in = null; try {//from w ww . j a v a2 s . c o m final URL url = new URL(urlString); urlConnection = (HttpURLConnection) url.openConnection(); in = new BufferedInputStream(urlConnection.getInputStream(), 8 * 1024); out = new BufferedOutputStream(outputStream, 8 * 1024); int b; while ((b = in.read()) != -1) { out.write(b); } return true; } catch (final IOException e) { e.printStackTrace(); } finally { if (urlConnection != null) { urlConnection.disconnect(); } try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (final IOException e) { e.printStackTrace(); } } return false; }
From source file:Main.java
/** * // w ww .ja v a 2 s . c om * @param zipFile * zip file * @param folderName * folder to load * @return list of entry in the folder * @throws ZipException * @throws IOException */ public static List<ZipEntry> loadFiles(File zipFile, String folderName) throws ZipException, IOException { Log.d("loadFiles", folderName); long start = System.currentTimeMillis(); FileInputStream fis = new FileInputStream(zipFile); BufferedInputStream bis = new BufferedInputStream(fis); ZipInputStream zis = new ZipInputStream(bis); ZipEntry zipEntry = null; List<ZipEntry> list = new LinkedList<ZipEntry>(); String folderLowerCase = folderName.toLowerCase(); int counter = 0; while ((zipEntry = zis.getNextEntry()) != null) { counter++; String zipEntryName = zipEntry.getName(); Log.d("loadFiles.zipEntry.getName()", zipEntryName); if (zipEntryName.toLowerCase().startsWith(folderLowerCase) && !zipEntry.isDirectory()) { list.add(zipEntry); } } Log.d("Loaded 1", counter + " files, took: " + (System.currentTimeMillis() - start) + " milliseconds."); zis.close(); bis.close(); fis.close(); return list; }
From source file:gemlite.core.util.RSAUtils.java
public static byte[] readBytes(String filePath) { byte[] content = new byte[0]; File file = new File(filePath); if (file.exists() && file.isFile()) try {/* ww w . jav a 2 s. c o m*/ InputStream in = new FileInputStream(file); BufferedInputStream bufin = new BufferedInputStream(in); int buffSize = 1024; ByteArrayOutputStream out = new ByteArrayOutputStream(buffSize); byte[] temp = new byte[buffSize]; int size = 0; while ((size = bufin.read(temp)) != -1) { out.write(temp, 0, size); } bufin.close(); content = out.toByteArray(); } catch (Exception e) { LogUtil.getCoreLog().warn("readKey file :{} failure :{}", filePath, e); } return content; }
From source file:FacebookImageLoader.java
public static Bitmap loadImageFromFile(final String file, final int maxDimension, boolean exactResize) { // Check input if (file == null || file.length() == 0) { return null; }//from ww w.j av a 2 s. c o m BufferedInputStream is = null; Bitmap image = null; if (exactResize) { // caller wants the output bitmap's max dimension scaled exactly // as passed in. This is slower. try { is = new BufferedInputStream(new FileInputStream(file), BUFFER_SIZE); image = BitmapFactory.decodeStream(is); is.close(); } catch (FileNotFoundException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } catch (OutOfMemoryError e) { // don't return, we'll try again with an inexact resize image = null; } if (image != null) { return processImageFromBitmap(image, maxDimension); } } // Caller does not need an exact image resize; we can achieve // "ballpark" using inSampleSize to save time and memory. BitmapFactory.Options opts = getImageSizeFromFile(file); if (opts == null) { return null; } // Calculate the resize ratio. Make the longest side // somewhere in the vicinity of 'maxDimension' pixels. int scaler = 1; int maxSide = Math.max(opts.outWidth, opts.outHeight); if (maxSide > maxDimension) { float ratio = (float) maxSide / (float) maxDimension; scaler = Math.round(ratio); } opts.inJustDecodeBounds = false; opts.inSampleSize = scaler; // This time we'll load the image for real, but with // inSampleSize set which will scale the image down as it is // loaded. try { is = new BufferedInputStream(new FileInputStream(file), BUFFER_SIZE); image = BitmapFactory.decodeStream(is, null, opts); is.close(); } catch (FileNotFoundException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } catch (OutOfMemoryError e) { e.printStackTrace(); return null; } return image; }
From source file:com.ibuildapp.romanblack.CataloguePlugin.imageloader.Utils.java
public static String downloadFile(Context context, String url, String md5) { final int BYTE_ARRAY_SIZE = 8024; final int CONNECTION_TIMEOUT = 30000; final int READ_TIMEOUT = 30000; try {//from w w w .j a v a 2 s .c o m for (int i = 0; i < 3; i++) { URL fileUrl = new URL(URLDecoder.decode(url)); HttpURLConnection connection = (HttpURLConnection) fileUrl.openConnection(); connection.setConnectTimeout(CONNECTION_TIMEOUT); connection.setReadTimeout(READ_TIMEOUT); connection.connect(); int status = connection.getResponseCode(); if (status >= HttpStatus.SC_BAD_REQUEST) { connection.disconnect(); continue; } BufferedInputStream bufferedInputStream = new BufferedInputStream(connection.getInputStream()); File file = new File(StaticData.getCachePath(context) + md5); if (!file.exists()) { new File(StaticData.getCachePath(context)).mkdirs(); file.createNewFile(); } FileOutputStream fileOutputStream = new FileOutputStream(file, false); int byteCount; byte[] buffer = new byte[BYTE_ARRAY_SIZE]; while ((byteCount = bufferedInputStream.read(buffer, 0, BYTE_ARRAY_SIZE)) != -1) fileOutputStream.write(buffer, 0, byteCount); bufferedInputStream.close(); fileOutputStream.flush(); fileOutputStream.close(); return file.getAbsolutePath(); } } catch (Exception e) { e.printStackTrace(); return null; } return null; }
From source file:com.pieframework.runtime.utils.Zipper.java
public static void unzip(String zipFile, String toDir) throws ZipException, IOException { int BUFFER = 2048; File file = new File(zipFile); ZipFile zip = new ZipFile(file); String newPath = toDir;// ww w. ja v a 2s .c o m File toDirectory = new File(newPath); if (!toDirectory.exists()) { toDirectory.mkdir(); } Enumeration zipFileEntries = zip.entries(); // Process each entry while (zipFileEntries.hasMoreElements()) { // grab a zip file entry ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); String currentEntry = entry.getName(); File destFile = new File(newPath, FilenameUtils.separatorsToSystem(currentEntry)); //System.out.println(currentEntry); File destinationParent = destFile.getParentFile(); // create the parent directory structure if needed destinationParent.mkdirs(); if (!entry.isDirectory()) { BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry)); int currentByte; // establish buffer for writing file byte data[] = new byte[BUFFER]; // write the current file to disk FileOutputStream fos = new FileOutputStream(destFile); BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER); // read and write until last byte is encountered while ((currentByte = is.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, currentByte); } dest.flush(); dest.close(); is.close(); } } zip.close(); }
From source file:Main.java
public static void unzip(URL _url, URL _dest, boolean _remove_top) { int BUFFER_SZ = 2048; File file = new File(_url.getPath()); String dest = _dest.getPath(); new File(dest).mkdir(); try {/*from w ww. j av a 2 s . c om*/ ZipFile zip = new ZipFile(file); Enumeration<? extends ZipEntry> zipFileEntries = zip.entries(); // Process each entry while (zipFileEntries.hasMoreElements()) { // grab a zip file entry ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); String currentEntry = entry.getName(); if (_remove_top) currentEntry = currentEntry.substring(currentEntry.indexOf('/'), currentEntry.length()); File destFile = new File(dest, currentEntry); //destFile = new File(newPath, destFile.getName()); File destinationParent = destFile.getParentFile(); // create the parent directory structure if needed destinationParent.mkdirs(); if (!entry.isDirectory()) { BufferedInputStream is; is = new BufferedInputStream(zip.getInputStream(entry)); int currentByte; // establish buffer for writing file byte data[] = new byte[BUFFER_SZ]; // write the current file to disk FileOutputStream fos = new FileOutputStream(destFile); BufferedOutputStream dst = new BufferedOutputStream(fos, BUFFER_SZ); // read and write until last byte is encountered while ((currentByte = is.read(data, 0, BUFFER_SZ)) != -1) { dst.write(data, 0, currentByte); } dst.flush(); dst.close(); is.close(); } /* if (currentEntry.endsWith(".zip")) { // found a zip file, try to open extractFolder(destFile.getAbsolutePath()); }*/ } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:emperior.Main.java
private static void readPropertyFile() throws Exception { Properties properties = new Properties(); try {/*from ww w . j a v a 2 s. co m*/ BufferedInputStream stream = new BufferedInputStream(new FileInputStream("Emperior.properties")); properties.load(stream); stream.close(); String[] manualOrder_arr_source = null; if (properties.getProperty("test") != null) commandMap.put("test", properties.getProperty("test")); if (properties.getProperty("run") != null) commandMap.put("run", properties.getProperty("run")); if (properties.getProperty("folder") != null) commandMap.put("folder", properties.getProperty("folder")); if (properties.getProperty("applicant") != null) applicant = properties.getProperty("applicant"); if (properties.getProperty("tasktypes") != null) { String[] tempArray = properties.getProperty("tasktypes").split(","); for (String s : tempArray) { tasktypes.add(s); } } if (properties.getProperty("startwithtype") != null) activeType = Integer.parseInt(properties.getProperty("startwithtype")); if (properties.getProperty("manualorder") != null) { String source = properties.getProperty("manualorder"); manualOrder_arr_source = source.split(","); } String resumetask = ""; if (properties.getProperty("resumetask") != null) { resumetask = properties.getProperty("resumetask"); if (resumetask.equals("finished")) { JOptionPane.showMessageDialog(null, "All tasks have been finished. If this is not the case Emperior has to be reset. Emperior is closing now."); System.exit(0); } } if (properties.getProperty("adminmode") != null) { adminmode = properties.getProperty("adminmode").equals("1"); } if (properties.getProperty("adminpassword") != null) { admin_password = properties.getProperty("adminpassword"); } if (properties.getProperty("startedwith") != null) { startedWith = properties.getProperty("startedwith"); } if (properties.getProperty("group") != null) { group = properties.getProperty("group"); } handleCommands(); if (manualOrder_arr_source != null) { boolean correctFormat = true; for (String s : manualOrder_arr_source) { correctFormat = checkManualOrderFormat(s); if (!correctFormat) break; } if (correctFormat) { for (String s : manualOrder_arr_source) { manualOrder.add(s); } } if (!adminmode) { if (tasks.size() != 0) { testStartedWith(); if (manualOrder != null && manualOrder.size() != 0) { String[] name_parts; String firsttask = ""; if (resumetask.trim().length() != 0) { //System.out.println(resumetask); name_parts = resumetask.split("_"); firsttask = resumetask; manualOrderPos = manualOrder.indexOf(resumetask); resuming = true; } else { name_parts = manualOrder.get(0).split("_"); firsttask = manualOrder.get(0); manualOrderPos = 0; resuming = false; } activeTask = tasks.indexOf(name_parts[1]); activeType = tasktypes.indexOf(name_parts[0]); //System.out.println(activeTask + " " + activeType); mainFrame.setExperimentFilesFolderPath( experimentFilesFolder + File.separator + firsttask); } else { String[] name_parts; if (resumetask.trim().length() != 0) { name_parts = resumetask.split("_"); activeTask = tasks.indexOf(name_parts[1]); activeType = tasktypes.indexOf(name_parts[0]); resuming = true; } else { activeTask = 0; activeType = 0; resuming = false; } String newTask = tasktypes.get(activeType) + "_" + tasks.get(activeTask); mainFrame .setExperimentFilesFolderPath(experimentFilesFolder + File.separator + newTask); } } } else { mainFrame.setExperimentFilesFolderPath(experimentFilesFolder); } } } catch (IOException e) { } }
From source file:fr.paris.lutece.plugins.upload.web.UploadJspBean.java
/** * Copies data from an input stream to an output stream. * @param inStream The input stream//ww w .j a v a 2 s.c om * @param outStream The output stream * @throws IOException If an I/O error occurs */ private static void copyStream(InputStream inStream, OutputStream outStream) throws IOException { BufferedInputStream inBufferedStream = new BufferedInputStream(inStream); BufferedOutputStream outBufferedStream = new BufferedOutputStream(outStream); int nByte = 0; while ((nByte = inBufferedStream.read()) > -1) { outBufferedStream.write(nByte); } outBufferedStream.close(); inBufferedStream.close(); }
From source file:com.chinamobile.bcbsp.fault.tools.Zip.java
/** * Compress files to *.zip.//from w w w . jav a 2 s . c o m * @param fileName * file name to compress * @return compressed file. */ public static String compress(String fileName) { String targetFile = null; File sourceFile = new File(fileName); Vector<File> vector = getAllFiles(sourceFile); try { if (sourceFile.isDirectory()) { targetFile = fileName + ".zip"; } else { char ch = '.'; targetFile = fileName.substring(0, fileName.lastIndexOf(ch)) + ".zip"; } BufferedInputStream bis = null; BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(targetFile)); ZipOutputStream zipos = new ZipOutputStream(bos); byte[] data = new byte[BUFFER]; if (vector.size() > 0) { for (int i = 0; i < vector.size(); i++) { File file = vector.get(i); zipos.putNextEntry(new ZipEntry(getEntryName(fileName, file))); bis = new BufferedInputStream(new FileInputStream(file)); int count; while ((count = bis.read(data, 0, BUFFER)) != -1) { zipos.write(data, 0, count); } bis.close(); zipos.closeEntry(); } zipos.close(); bos.close(); return targetFile; } else { File zipNullfile = new File(targetFile); zipNullfile.getParentFile().mkdirs(); zipNullfile.mkdir(); return zipNullfile.getAbsolutePath(); } } catch (IOException e) { LOG.error("[compress]", e); return "error"; } }