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:egovframework.oe1.cms.com.service.EgovOe1Properties.java

/**
 * ??  ?? Key  ? ? (Globals.java )/* w  w w.  j a v  a  2 s.c  om*/
 * 
 * @param ???
 *            ? ? Key
 * @return ??  ?? Key  ? 
 */
public static String getProperty(String keyName) {
    // System.out.println("====="+globalsPropertiesFile);
    String value = errCode;
    value = "99";
    debug(globalsPropertiesFile + " : " + keyName);
    FileInputStream fis = null;
    java.io.BufferedInputStream bis = null;
    try {
        Properties props = new Properties();

        String file1 = globalsPropertiesFile.replace('\\', FILE_SEPARATOR).replace('/', FILE_SEPARATOR);
        fis = new FileInputStream(file1);
        bis = new java.io.BufferedInputStream(fis);
        props.load(bis);
        value = props.getProperty(keyName).trim();
        props.clear();
    } catch (java.io.FileNotFoundException fne) {

        debug(fne);
    } catch (java.io.IOException ioe) {
        debug(ioe);
    } catch (java.lang.Exception e) {
        debug(e);
    } finally {
        if (fis != null)
            try {
                fis.close();
            } catch (Exception e) {
                debug(e);
            }
        if (bis != null)
            try {
                bis.close();
            } catch (Exception e) {
                debug(e);
            }
    }
    return value;
}

From source file:com.youqude.storyflow.weibo.Utility.java

/**
 * Upload image into output stream ./*from  w w w .j a  va2 s.  c  om*/
 * 
 * @param out
 *            : output stream for uploading weibo
 * @param imgpath
 *            : bitmap for uploading
 * @return void
 */
public 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.JPEG, 100, 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:moskitt4me.repositoryClient.core.util.RepositoryClientUtil.java

public static void addFileToZip(File file, ZipOutputStream zos) throws Exception {

    zos.putNextEntry(new ZipEntry(file.getName()));

    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));

    long bytesRead = 0;
    byte[] bytesIn = new byte[1024];
    int read = 0;

    while ((read = bis.read(bytesIn)) != -1) {
        zos.write(bytesIn, 0, read);/*from www.  ja v  a 2s .  c o  m*/
        bytesRead += read;
    }

    zos.closeEntry();
    bis.close();
}

From source file:net.librec.util.FileUtil.java

/**
 * Zip a given folder/*from w w  w  .  j  ava2s. com*/
 *
 * @param dirPath    a given folder: must be all files (not sub-folders)
 * @param filePath   zipped file
 * @throws Exception if error occurs
 */
public static void zipFolder(String dirPath, String filePath) throws Exception {
    File outFile = new File(filePath);
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outFile));
    int bytesRead;
    byte[] buffer = new byte[1024];
    CRC32 crc = new CRC32();
    for (File file : listFiles(dirPath)) {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        crc.reset();
        while ((bytesRead = bis.read(buffer)) != -1) {
            crc.update(buffer, 0, bytesRead);
        }
        bis.close();

        // Reset to beginning of input stream
        bis = new BufferedInputStream(new FileInputStream(file));
        ZipEntry entry = new ZipEntry(file.getName());
        entry.setMethod(ZipEntry.STORED);
        entry.setCompressedSize(file.length());
        entry.setSize(file.length());
        entry.setCrc(crc.getValue());
        zos.putNextEntry(entry);
        while ((bytesRead = bis.read(buffer)) != -1) {
            zos.write(buffer, 0, bytesRead);
        }
        bis.close();
    }
    zos.close();

    LOG.debug("A zip-file is created to: " + outFile.getPath());
}

From source file:gov.nih.nci.nbia.textsupport.NCIADicomTextObject.java

public static List<DicomTagDTO> getTagElements(File file) throws Exception {
    DcmParserFactory pFact = DcmParserFactory.getInstance();
    DcmObjectFactory oFact = DcmObjectFactory.getInstance();
    BufferedInputStream in = null;
    List<DicomTagDTO> allElements = new ArrayList<DicomTagDTO>();
    try {//from   w w  w . j av a2  s. c o  m
        in = new BufferedInputStream(new FileInputStream(file));

        DcmParser parser = pFact.newDcmParser(in);
        FileFormat fileFormat = parser.detectFileFormat();

        if (fileFormat == null) {
            throw new IOException("Unrecognized file format: " + file);
        }

        Dataset dataset = oFact.newDataset();
        parser.setDcmHandler(dataset.getDcmHandler());
        //Parse the file, but don't get the pixels in order to save heap space
        parser.parseDcmFile(fileFormat, Tags.PixelData);
        //See if this is a real image.
        boolean isImage = (parser.getReadTag() == Tags.PixelData);
        //Get the charset in case we need it for manifest processing.

        in.close();

        SpecificCharacterSet cs = dataset.getSpecificCharacterSet();
        allElements.addAll(walkDataset(dataset.getFileMetaInfo(), cs, ""));
        allElements.addAll(walkDataset(dataset, cs, ""));
        parser = null;

    } catch (Exception exception) {
        if (in != null) {
            in.close();
        }

        throw exception;
    }
    return allElements;
}

From source file:org.alfresco.selenium.FetchUtil.java

/**
 * Retrieve file with authentication, using {@link WebDriver} cookie we
 * keep the session and use HttpClient to download files that requires
 * user to be authenticated. /*from  w  ww.  j av  a  2 s. co m*/
 * @param resourceUrl path to file to download
 * @param driver {@link WebDriver}
 * @param output path to output the file
 * @throws IOException if error
 */
protected static File retrieveFile(final String resourceUrl, final CloseableHttpClient client,
        final File output) throws IOException {
    HttpGet httpGet = new HttpGet(resourceUrl);
    BufferedOutputStream bos = null;
    BufferedInputStream bis = null;
    HttpResponse response = null;
    try {
        response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        bos = new BufferedOutputStream(new FileOutputStream(output));
        bis = new BufferedInputStream(entity.getContent());
        int inByte;
        while ((inByte = bis.read()) != -1)
            bos.write(inByte);
        HttpClientUtils.closeQuietly(response);
    } catch (Exception e) {
        logger.error("Unable to fetch file " + resourceUrl, e);
    } finally {
        if (response != null) {
            HttpClientUtils.closeQuietly(response);
        }
        if (bis != null) {
            bis.close();
        }
        if (bos != null) {
            bos.close();
        }
    }
    return output;
}

From source file:com.elastica.helper.FileUtility.java

public static void extractJar(final String storeLocation, final Class<?> clz) throws IOException {
    File firefoxProfile = new File(storeLocation);
    String location = clz.getProtectionDomain().getCodeSource().getLocation().getFile();

    JarFile jar = new JarFile(location);
    System.out.println("Extracting jar file::: " + location);
    firefoxProfile.mkdir();//w  w w  . java 2  s.c  om

    Enumeration<?> jarFiles = jar.entries();
    while (jarFiles.hasMoreElements()) {
        ZipEntry entry = (ZipEntry) jarFiles.nextElement();
        String currentEntry = entry.getName();
        File destinationFile = new File(storeLocation, currentEntry);
        File destinationParent = destinationFile.getParentFile();

        // create the parent directory structure if required
        destinationParent.mkdirs();
        if (!entry.isDirectory()) {
            BufferedInputStream is = new BufferedInputStream(jar.getInputStream(entry));
            int currentByte;

            // buffer for writing file
            byte[] data = new byte[BUFFER];

            // write the current file to disk
            FileOutputStream fos = new FileOutputStream(destinationFile);
            BufferedOutputStream destination = new BufferedOutputStream(fos, BUFFER);

            // read and write till last byte
            while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                destination.write(data, 0, currentByte);
            }

            destination.flush();
            destination.close();
            is.close();
        }
    }

    FileUtils.deleteDirectory(new File(storeLocation + "\\META-INF"));
    if (OSUtility.isWindows()) {
        new File(storeLocation + "\\" + clz.getCanonicalName().replaceAll("\\.", "\\\\") + ".class").delete();
    } else {
        new File(storeLocation + "/" + clz.getCanonicalName().replaceAll("\\.", "/") + ".class").delete();
    }
}

From source file:most.voip.api.Utils.java

/**
 * Load UTF8withBOM or any ansi text file.
 * @param filename// w ww . ja  v a 2  s.c  om
 * @return  
 * @throws java.io.IOException
 */
public static String loadFileAsString(String filename) throws java.io.IOException {
    final int BUFLEN = 1024;
    BufferedInputStream is = new BufferedInputStream(new FileInputStream(filename), BUFLEN);
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream(BUFLEN);
        byte[] bytes = new byte[BUFLEN];
        boolean isUTF8 = false;
        int read, count = 0;
        while ((read = is.read(bytes)) != -1) {
            if (count == 0 && bytes[0] == (byte) 0xEF && bytes[1] == (byte) 0xBB && bytes[2] == (byte) 0xBF) {
                isUTF8 = true;
                baos.write(bytes, 3, read - 3); // drop UTF8 bom marker
            } else {
                baos.write(bytes, 0, read);
            }
            count += read;
        }
        return isUTF8 ? new String(baos.toByteArray(), "UTF-8") : new String(baos.toByteArray());
    } finally {
        try {
            is.close();
        } catch (Exception ex) {
        }
    }
}

From source file:Main.java

/**
 * Uncompresses zipped files/*from   w  w  w .  ja  v a  2  s .  c  om*/
 * @param zippedFile The file to uncompress
 * @param destinationDir Where to put the files
 * @return  list of unzipped files
 * @throws java.io.IOException thrown if there is a problem finding or writing the files
 */
public static List<File> unzip(File zippedFile, File destinationDir) throws IOException {
    int buffer = 2048;

    List<File> unzippedFiles = new ArrayList<File>();

    BufferedOutputStream dest;
    BufferedInputStream is;
    ZipEntry entry;
    ZipFile zipfile = new ZipFile(zippedFile);
    Enumeration e = zipfile.entries();
    while (e.hasMoreElements()) {
        entry = (ZipEntry) e.nextElement();

        is = new BufferedInputStream(zipfile.getInputStream(entry));
        int count;
        byte data[] = new byte[buffer];

        File destFile;

        if (destinationDir != null) {
            destFile = new File(destinationDir, entry.getName());
        } else {
            destFile = new File(entry.getName());
        }

        FileOutputStream fos = new FileOutputStream(destFile);
        dest = new BufferedOutputStream(fos, buffer);
        try {
            while ((count = is.read(data, 0, buffer)) != -1) {
                dest.write(data, 0, count);
            }

            unzippedFiles.add(destFile);
        } finally {
            dest.flush();
            dest.close();
            is.close();
        }
    }

    return unzippedFiles;
}

From source file:org.dasein.cloud.aws.storage.S3Method.java

static public byte[] computeMD5Hash(InputStream is) throws NoSuchAlgorithmException, IOException {
    BufferedInputStream bis = new BufferedInputStream(is);

    try {/*from   w  w w  .java 2 s  . co  m*/
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        byte[] buffer = new byte[16384];
        int bytesRead = -1;
        while ((bytesRead = bis.read(buffer, 0, buffer.length)) != -1) {
            messageDigest.update(buffer, 0, bytesRead);
        }
        return messageDigest.digest();
    } finally {
        try {
            bis.close();
        } catch (Exception e) {
            System.err.println("Unable to close input stream of hash candidate: " + e);
        }
    }
}