Example usage for java.io BufferedInputStream close

List of usage examples for java.io BufferedInputStream close

Introduction

In this page you can find the example usage for java.io BufferedInputStream close.

Prototype

public void close() throws IOException 

Source Link

Document

Closes this input stream and releases any system resources associated with the stream.

Usage

From source file:it.geosolutions.tools.compress.file.reader.TarReader.java

/**
 * A method to read tar file:/*from   w w w. j ava 2 s . com*/
 * extract its content to the 'destDir' file (which could be
 * a directory or a file depending on the srcF file content)
 * @throws CompressorException 
 */
public static void readTar(File srcF, File destDir) throws Exception {
    if (destDir == null)
        throw new IllegalArgumentException("Unable to extract to a null destination dir");
    if (!destDir.canWrite() && !destDir.mkdirs())
        throw new IllegalArgumentException("Unable to extract to a not writeable destination dir: " + destDir);

    FileInputStream fis = null;
    TarArchiveInputStream tis = null;
    BufferedInputStream bis = null;
    try {
        fis = new FileInputStream(srcF);
        bis = new BufferedInputStream(fis);
        tis = new TarArchiveInputStream(bis);

        TarArchiveEntry te = null;
        while ((te = tis.getNextTarEntry()) != null) {

            File curr_dest = new File(destDir, te.getName());
            if (te.isDirectory()) {
                // create destination folder
                if (!curr_dest.exists())
                    curr_dest.mkdirs();
            } else {
                writeFile(curr_dest, tis);
            }
        }
    } finally {
        if (tis != null) {
            try {
                tis.close();
            } catch (IOException ioe) {
            }
        }
        if (bis != null) {
            try {
                bis.close();
            } catch (IOException ioe) {
            }
        }
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException ioe) {
            }
        }

    }
}

From source file:com.android.volley.toolbox.http.HurlStack.java

/**
 * Perform a multipart request on a connection
 *
 * @param connection The Connection to perform the multi part request
 * @param request    param additionalHeaders
 *                   param multipartParams
 *                   The params to add to the Multi Part request
 *                   param filesToUpload
 *                   The files to upload
 * @throws ProtocolException/*ww w  . j  a v a 2s .com*/
 */
private static void setConnectionParametersForMultipartRequest(HttpURLConnection connection, Request<?> request)
        throws IOException, ProtocolException {

    Map<String, File> filesToUpload = request.getFilesToUpload();
    if (filesToUpload != null) {
        for (String key : filesToUpload.keySet()) {
            File file = filesToUpload.get(key);

            if (file == null || !file.exists()) {
                throw new IOException(String.format("File not found: %s", file.getAbsolutePath()));
            }
            if (file.isDirectory()) {
                throw new IOException(String.format("File is a directory: %s", file.getAbsolutePath()));
            }
        }
    }

    final int curTime = (int) (System.currentTimeMillis() / 1000);
    final String boundary = BOUNDARY_PREFIX + curTime;
    StringBuilder sb = new StringBuilder();
    Map<String, MultiPartParam> multipartParams = request.getMultiPartParams();
    for (String key : multipartParams.keySet()) {
        MultiPartParam param = multipartParams.get(key);

        sb.append(boundary).append(CRLF)
                .append(String.format(HEADER_CONTENT_DISPOSITION + COLON_SPACE + FORM_DATA, key)).append(CRLF)
                .append(HEADER_CONTENT_TYPE + COLON_SPACE).append(param.contentType).append(CRLF).append(CRLF)
                .append(param.value).append(CRLF);
    }
    final String charset = request.getParamsEncoding();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setRequestProperty(HEADER_CONTENT_TYPE, String.format(CONTENT_TYPE_MULTIPART, charset, curTime));
    //        connection.setChunkedStreamingMode(0);

    PrintWriter writer = null;
    try {
        OutputStream out = connection.getOutputStream();
        writer = new PrintWriter(new OutputStreamWriter(out, charset), true);

        writer.append(sb).flush();

        for (String key : filesToUpload.keySet()) {

            File file = filesToUpload.get(key);

            writer.append(boundary).append(CRLF)
                    .append(String.format(
                            HEADER_CONTENT_DISPOSITION + COLON_SPACE + FORM_DATA + SEMICOLON_SPACE + FILENAME,
                            key, file.getName()))
                    .append(CRLF).append(HEADER_CONTENT_TYPE + COLON_SPACE + CONTENT_TYPE_OCTET_STREAM)
                    .append(CRLF).append(HEADER_CONTENT_TRANSFER_ENCODING + COLON_SPACE + BINARY).append(CRLF)
                    .append(CRLF).flush();

            BufferedInputStream input = null;
            try {
                input = new BufferedInputStream(new FileInputStream(file));
                int bufferLength = 0;

                byte[] buffer = new byte[1024];
                while ((bufferLength = input.read(buffer)) > 0) {
                    out.write(buffer, 0, bufferLength);
                }
                out.flush(); // Important! Output cannot be closed. Close of
                // writer will close
                // output as well.
            } finally {
                if (input != null)
                    try {
                        input.close();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
            }
            writer.append(CRLF).flush(); // CRLF is important! It indicates
            // end of binary
            // boundary.
        }

        // End of multipart/form-data.
        writer.append(boundary).append(BOUNDARY_PREFIX).append(CRLF).flush();

    } catch (Exception e) {
        e.printStackTrace();

    } finally {
        if (writer != null) {
            writer.close();
        }
    }
}

From source file:it.geosolutions.geobatch.destination.common.utils.RemoteBrowserUtils.java

/**
 * Download a remote file to a local path
 * //from w w  w .  j ava  2  s .c  o m
 * @param fo
 * @param localPath
 * @return File with the content
 * @throws IOException
 */
public static File downloadFile(FileObject fo, String localPath) throws IOException {

    // open input stream from the remote file
    BufferedInputStream is = null;
    OutputStream os = null;

    try {
        is = new BufferedInputStream(fo.getContent().getInputStream());
        // open output stream to local file
        os = new BufferedOutputStream(new FileOutputStream(localPath));
        int c;
        // do copying
        while ((c = is.read()) != -1) {
            os.write(c);
        }
    } catch (FileSystemException e) {
        throw new IOException("Can't open input stream", e);
    } finally {
        if (os != null) {
            os.close();
        }
        if (is != null) {
            is.close();
        }
    }

    return new File(localPath);
}

From source file:com.blork.anpod.util.BitmapUtils.java

private static Bitmap decodeStream(InputStream is, int desiredWidth, int desiredHeight) {
    Bitmap b = null;//from   ww  w.  j ava 2  s .com
    try {
        //Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;

        BufferedInputStream bis = new BufferedInputStream(is);
        bis.mark(Integer.MAX_VALUE);

        BitmapFactory.decodeStream(bis, null, o);
        bis.reset();

        int scale = 1;
        if (o.outHeight > desiredHeight || o.outWidth > desiredWidth) {
            scale = (int) Math.pow(2,
                    (int) Math.round(Math.log(
                            Math.max(desiredHeight, desiredWidth) / (double) Math.max(o.outHeight, o.outWidth))
                            / Math.log(0.5)));
        }

        //Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        o2.inDither = true;
        o2.inPurgeable = true;

        b = BitmapFactory.decodeStream(bis, null, o2);
        bis.close();
        is.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return b;
}

From source file:org.openo.nfvo.jujuvnfmadapter.common.DownloadCsarManager.java

/**
 * unzip CSAR packge/* w  w  w.  ja  v  a  2  s.c o  m*/
 * @param fileName filePath
 * @return
 */
public static int unzipCSAR(String fileName, String filePath) {
    final int BUFFER = 2048;
    int status = 0;

    try {
        ZipFile zipFile = new ZipFile(fileName);
        Enumeration emu = zipFile.entries();
        int i = 0;
        while (emu.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) emu.nextElement();
            //read directory as file first,so only need to create directory
            if (entry.isDirectory()) {
                new File(filePath + entry.getName()).mkdirs();
                continue;
            }
            BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
            File file = new File(filePath + entry.getName());
            //Because that is random to read zipfile,maybe the file is read first
            //before the directory is read,so we need to create directory first.
            File parent = file.getParentFile();
            if (parent != null && (!parent.exists())) {
                parent.mkdirs();
            }
            FileOutputStream fos = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER);

            int count;
            byte data[] = new byte[BUFFER];
            while ((count = bis.read(data, 0, BUFFER)) != -1) {
                bos.write(data, 0, count);
            }
            bos.flush();
            bos.close();
            bis.close();

            if (entry.getName().endsWith(".zip")) {
                File subFile = new File(filePath + entry.getName());
                if (subFile.exists()) {
                    int subStatus = unzipCSAR(filePath + entry.getName(), subFile.getParent() + "/");
                    if (subStatus != 0) {
                        LOG.error("sub file unzip fail!" + subFile.getName());
                        status = Constant.UNZIP_FAIL;
                        return status;
                    }
                }
            }
        }
        status = Constant.UNZIP_SUCCESS;
        zipFile.close();
    } catch (Exception e) {
        status = Constant.UNZIP_FAIL;
        e.printStackTrace();
    }
    return status;
}

From source file:hd3gtv.mydmam.metadata.RenderedFile.java

/**
 * Test presence and validity for file.//  w  w w.j  av a 2 s .c o  m
 */
public static RenderedFile import_from_entry(RenderedContent content, String metadata_reference_id,
        boolean check_hash) throws IOException {
    if (content == null) {
        throw new NullPointerException("\"content\" can't to be null");
    }

    if (metadata_reference_id == null) {
        throw new NullPointerException("\"metadata_reference_id\" can't to be null");
    }

    if (local_directory == null) {
        throw new IOException("No configuration is set !");
    }
    if (local_directory.exists() == false) {
        throw new IOException("Invalid configuration is set !");
    }

    RenderedFile result = new RenderedFile();

    StringBuffer sb_rendered_file = new StringBuffer();
    sb_rendered_file.append(local_directory.getCanonicalPath());
    sb_rendered_file.append(File.separator);
    sb_rendered_file.append(metadata_reference_id.substring(0, 6));
    sb_rendered_file.append(File.separator);
    sb_rendered_file.append(metadata_reference_id.substring(6));
    sb_rendered_file.append(File.separator);
    sb_rendered_file.append(content.name);
    result.rendered_file = new File(sb_rendered_file.toString());

    if (result.rendered_file.exists() == false) {
        throw new FileNotFoundException("Can't found rendered file " + sb_rendered_file.toString());
    }

    if (result.rendered_file.length() != content.size) {
        throw new FileNotFoundException(
                "Rendered file has not the expected size " + sb_rendered_file.toString());
    }

    if (check_hash) {
        result.rendered_digest = (String) content.hash;

        MessageDigest mdigest = null;
        try {
            mdigest = MessageDigest.getInstance(digest_algorithm);
        } catch (NoSuchAlgorithmException e) {
        }
        BufferedInputStream source_stream = new BufferedInputStream(new FileInputStream(result.rendered_file),
                0xFFF);
        int len;
        byte[] buffer = new byte[0xFFF];
        while ((len = source_stream.read(buffer)) > 0) {
            mdigest.update(buffer, 0, len);
        }
        source_stream.close();
        String file_digest = MyDMAM.byteToString(mdigest.digest());

        if (file_digest.equalsIgnoreCase(result.rendered_digest) == false) {
            Log2Dump dump = new Log2Dump();
            dump.add("source", sb_rendered_file);
            dump.add("source", file_digest);
            dump.add("expected", content);
            dump.add("expected", result.rendered_digest);
            Log2.log.error("Invalid " + digest_algorithm + " check", null, dump);
            throw new FileNotFoundException(
                    "Rendered file has not the expected content " + sb_rendered_file.toString());
        }
    }
    result.rendered_mime = content.mime;
    result.consolidated = true;
    return result;
}

From source file:org.deeplearning4j.cli.api.flags.Properties.java

@Override
public <E> E value(String value) throws Exception {
    File file = new File(value);
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
    props.load(bis);/* ww  w . ja  v  a2 s  .  com*/
    bis.close();
    Configuration configuration = new Configuration();
    for (String key : props.stringPropertyNames()) {
        configuration.set(key, props.getProperty(key));
    }
    return (E) configuration;

}

From source file:com.dongfang.dicos.sina.UtilSina.java

/**
 * Upload image into output stream ./*from  www  . jav a  2 s .c o m*/
 * 
 * @param out
 *            : output stream for uploading weibo
 * @param imgpath
 *            : bitmap for uploading
 * @return void
 */
private static void imageContentToUpload(OutputStream out, Bitmap imgpath) throws WeiboException {
    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);
        imgpath.compress(CompressFormat.PNG, 75, out);
        out.write("\r\n".getBytes());
        out.write(("\r\n" + END_MP_BOUNDARY).getBytes());
    } catch (IOException e) {
        throw new WeiboException(e);
    } finally {
        if (null != bis) {
            try {
                bis.close();
            } catch (IOException e) {
                throw new WeiboException(e);
            }
        }
    }
}

From source file:ImageUtils.java

final public static ImageProperties getGifProperties(File file) throws FileNotFoundException, IOException {
    BufferedInputStream in = null;
    try {/*from  w  ww. j  ava2  s . co  m*/
        in = new BufferedInputStream(new FileInputStream(file));
        byte[] buf = new byte[10];
        int count = in.read(buf, 0, 10);
        if (count < 10) {
            throw new RuntimeException("Not a valid Gif file!");
        }
        if ((buf[0]) != (byte) 'G' || (buf[1]) != (byte) 'I' || (buf[2]) != (byte) 'F') {
            throw new RuntimeException("Not a valid Gif file!");
        }

        int w1 = (buf[6] & 0xff) | (buf[6] & 0x80);
        int w2 = (buf[7] & 0xff) | (buf[7] & 0x80);
        int h1 = (buf[8] & 0xff) | (buf[8] & 0x80);
        int h2 = (buf[9] & 0xff) | (buf[9] & 0x80);

        int width = w1 + (w2 << 8);
        int height = h1 + (h2 << 8);

        return (new ImageProperties(width, height, null, "gif"));

    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:XMLResourceBundleControl.java

  public ResourceBundle newBundle(String baseName, Locale locale, String format,
    ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException,
    IOException {//from   w w  w  . j a va2 s . c om

  if ((baseName == null) || (locale == null) || (format == null) || (loader == null)) {
    throw new NullPointerException();
  }
  ResourceBundle bundle = null;
  if (!format.equals(XML)) {
    return null;
  }

  String bundleName = toBundleName(baseName, locale);
  String resourceName = toResourceName(bundleName, format);
  URL url = loader.getResource(resourceName);
  if (url == null) {
    return null;
  }
  URLConnection connection = url.openConnection();
  if (connection == null) {
    return null;
  }
  if (reload) {
    connection.setUseCaches(false);
  }
  InputStream stream = connection.getInputStream();
  if (stream == null) {
    return null;
  }
  BufferedInputStream bis = new BufferedInputStream(stream);
  bundle = new XMLResourceBundle(bis);
  bis.close();

  return bundle;
}