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:com.aurel.track.util.PluginUtils.java

/**
 * Unzip this file into the given directory. If the zipFile is called "zipFile.zip",
 * the files will be placed into "targetDir/zipFile".
 * @param zipFile/*  w w  w  .ja va 2s  .  co  m*/
 * @param targetDir
 */
public static void unzipFileIntoDirectory(File zipFile, File targetDir) {
    try {
        LOGGER.debug("Expanding Genji extension file " + zipFile.getName());
        int BUFFER = 2048;
        File file = zipFile;
        ZipFile zip = new ZipFile(file);
        String newPath = targetDir + File.separator
                + zipFile.getName().substring(0, zipFile.getName().length() - 4);
        new File(newPath).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, 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 = new BufferedInputStream(zip.getInputStream(entry));
                int currentByte;
                // establish buffer for writing file
                byte data[] = new byte[BUFFER];
                // write the current file to disk
                LOGGER.debug("Unzipping " + destFile.getAbsolutePath());
                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();
            }
        }
    } catch (Exception e) {
        LOGGER.error(ExceptionUtils.getStackTrace(e));
    }
}

From source file:foam.littlej.android.app.net.MainHttpClient.java

public byte[] fetchImage2(String address) throws MalformedURLException, IOException {

    HttpResponse response;//from   w  w w .  j  a  va  2s  .co  m

    try {
        response = GetURL(address);
        int fileSize = (int) response.getEntity().getContentLength();
        if (fileSize < 0) {
            return null;
        }
        byte[] imageData = new byte[fileSize];

        BufferedInputStream istream = new BufferedInputStream(response.getEntity().getContent(),
                IO_BUFFER_SIZE);
        int bytesRead = 0;
        int offset = 0;
        while (bytesRead != -1 && offset < fileSize) {
            bytesRead = istream.read(imageData, offset, fileSize - offset);
            offset += bytesRead;
        }

        // clean up
        istream.close();
        return imageData;
    } catch (IOException e) {
        // android.util.Log.e("IO", "Could not load buddy icon: " + this,
        // e);

    }
    return null;
}

From source file:com.naryx.tagfusion.cfm.mail.cfMailMessageData.java

private void extractBody(Part Mess, cfArrayData AD, String attachURI, String attachDIR) throws Exception {

    if (Mess.isMimeType("multipart/*")) {

        Multipart mp = (Multipart) Mess.getContent();
        int count = mp.getCount();
        for (int i = 0; i < count; i++)
            extractBody(mp.getBodyPart(i), AD, attachURI, attachDIR);

    } else {// ww w .java  2 s .  c  om

        cfStructData sd = new cfStructData();

        String tmp = Mess.getContentType();
        if (tmp.indexOf(";") != -1)
            tmp = tmp.substring(0, tmp.indexOf(";"));

        sd.setData("mimetype", new cfStringData(tmp));

        String filename = getFilename(Mess);
        String dispos = getDisposition(Mess);

        MimeType messtype = new MimeType(tmp);
        // Note that we can't use Mess.isMimeType() here due to bug #2080
        if ((dispos == null || dispos.equalsIgnoreCase(Part.INLINE)) && messtype.match("text/*")) {

            Object content;
            String contentType = Mess.getContentType().toLowerCase();
            // support aliases of UTF-7 - UTF7, UNICODE-1-1-UTF-7, csUnicode11UTF7, UNICODE-2-0-UTF-7
            if (contentType.indexOf("utf-7") != -1 || contentType.indexOf("utf7") != -1) {
                InputStream ins = Mess.getInputStream();
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                IOUtils.copy(ins, bos);
                content = new String(UTF7Converter.convert(bos.toByteArray()));
            } else {
                try {
                    content = Mess.getContent();
                } catch (UnsupportedEncodingException e) {
                    content = Mess.getInputStream();
                } catch (IOException ioe) {
                    // This will happen on BD/Java when the attachment has no content
                    // NOTE: this is the fix for bug NA#3198.
                    content = "";
                }
            }

            if (content instanceof InputStream) {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                IOUtils.copy((InputStream) content, bos);
                sd.setData("content", new cfStringData(new String(bos.toByteArray())));
            } else {
                sd.setData("content", new cfStringData(content.toString()));
            }

            sd.setData("file", cfBooleanData.FALSE);
            sd.setData("filename", new cfStringData(filename == null ? "" : filename));

        } else if (attachDIR != null) {

            sd.setData("content", new cfStringData(""));

            if (filename == null || filename.length() == 0)
                filename = "unknownfile";

            filename = getAttachedFilename(attachDIR, filename);

            //--[ An attachment, save it out to disk
            try {
                BufferedInputStream in = new BufferedInputStream(Mess.getInputStream());
                BufferedOutputStream out = new BufferedOutputStream(
                        cfEngine.thisPlatform.getFileIO().getFileOutputStream(new File(attachDIR + filename)));
                IOUtils.copy(in, out);

                out.flush();
                out.close();
                in.close();

                sd.setData("file", cfBooleanData.TRUE);
                sd.setData("filename", new cfStringData(filename));
                if (attachURI.charAt(attachURI.length() - 1) != '/')
                    sd.setData("url", new cfStringData(attachURI + '/' + filename));
                else
                    sd.setData("url", new cfStringData(attachURI + filename));
                sd.setData("size", new cfNumberData((int) new File(attachDIR + filename).length()));

            } catch (Exception ignoreException) {
                // NOTE: this could happen when we don't have permission to write to the specified directory
                //       so let's log an error message to make this easier to debug.
                cfEngine.log("-] Failed to save attachment to " + attachDIR + filename + ", exception=["
                        + ignoreException.toString() + "]");
            }

        } else {
            sd.setData("file", cfBooleanData.FALSE);
            sd.setData("content", new cfStringData(""));
        }

        AD.addElement(sd);
    }
}

From source file:es.mityc.firmaJava.configuracion.Configuracion.java

/**
  * Este mtodo guarda la configuracin en el fichero SignXML.properties
  * @throws IOException //from w  w  w  .ja  v a  2 s .c  om
  */
public void guardarConfiguracion() throws IOException {
    StringBuffer paraGrabar = new StringBuffer();
    String linea;

    // La configuracin siempre se guarda en un fichero externo
    File dir = new File(System.getProperty(USER_HOME) + File.separator + getNombreDirExterno());
    if ((!dir.exists()) || (!dir.isDirectory())) {
        if (!dir.mkdir())
            return;
    }
    File fichero = new File(dir, getNombreFicheroExterno());
    log.trace("Salva fichero de configuracin en: " + fichero.getAbsolutePath());
    if (!fichero.exists()) {
        // Si el fichero externo no existe se crea fuera un copia
        // del fichero almacenado dentro del jar
        InputStream fis = getClass().getResourceAsStream(FICHERO_PROPIEDADES);
        BufferedInputStream bis = new BufferedInputStream(fis);
        FileOutputStream fos = new FileOutputStream(fichero);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        int length = bis.available();
        byte[] datos = new byte[length];
        bis.read(datos);
        bos.write(datos);
        bos.flush();
        bos.close();
        bis.close();
    }
    // AppPerfect: Falso positivo
    BufferedReader propiedades = new BufferedReader(new FileReader(fichero));

    linea = propiedades.readLine();
    while (linea != null) {
        StringTokenizer token = new StringTokenizer(linea, IGUAL);
        if (token.hasMoreTokens()) {
            String clave = token.nextToken().trim();
            if (configuracion.containsKey(clave)) {
                paraGrabar.append(clave);
                paraGrabar.append(IGUAL_ESPACIADO);
                paraGrabar.append(getValor(clave));
                paraGrabar.append(CRLF);
            } else {
                paraGrabar.append(linea);
                paraGrabar.append(CRLF);

            }
        } else
            paraGrabar.append(CRLF);
        linea = propiedades.readLine();
    }
    propiedades.close();

    //AppPerfect: Falso positivo
    FileWriter fw = new FileWriter(fichero);
    BufferedWriter bw = new BufferedWriter(fw);
    bw.write(String.valueOf(paraGrabar));
    bw.flush();
    bw.close();

}

From source file:edu.stanford.epad.epadws.handlers.dicom.DownloadUtil.java

public static boolean ZipAndStreamFiles(OutputStream out, List<String> fileNames, String dirPath) {

    File dir_file = new File(dirPath);
    int dir_l = dir_file.getAbsolutePath().length();
    ZipOutputStream zipout = new ZipOutputStream(out);
    zipout.setLevel(1);/*from ww  w.  j  a  va2  s  .  co m*/
    for (int i = 0; i < fileNames.size(); i++) {
        File f = (File) new File(dirPath + fileNames.get(i));
        if (f.canRead()) {
            log.debug("Adding file: " + f.getAbsolutePath());
            try {
                zipout.putNextEntry(new ZipEntry(f.getAbsolutePath().substring(dir_l + 1)));
            } catch (Exception e) {
                log.warning("Error adding to zip file", e);
                return false;
            }
            BufferedInputStream fr;
            try {
                fr = new BufferedInputStream(new FileInputStream(f));

                byte buffer[] = new byte[0xffff];
                int b;
                while ((b = fr.read(buffer)) != -1)
                    zipout.write(buffer, 0, b);

                fr.close();
                zipout.closeEntry();

            } catch (Exception e) {
                log.warning("Error closing zip file", e);
                return false;
            }
        }
    }

    try {
        zipout.finish();
        out.flush();
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }

    return true;

}

From source file:com.binroot.fatpita.BitmapManager.java

/**
 * http://ballardhack.wordpress.com/2010/04/10/loading-images-over-http-on-a-separate-thread-on-android/
 * Convenience method to retrieve a bitmap image from
 * a URL over the network. The built-in methods do
 * not seem to work, as they return a FileNotFound
 * exception./*from   w w  w . j a  v  a 2s.  c  om*/
 *
 * Note that this does not perform any threading --
 * it blocks the call while retrieving the data.
 *
 * @param url The URL to read the bitmap from.
 * @return A Bitmap image or null if an error occurs.
 */
public Bitmap readBitmapFromNetwork(String url, boolean saveToHistory) {

    InputStream is = null;
    BufferedInputStream bis = null;
    Bitmap bmp = null;

    while (bmp == null) {
        try {
            is = fetch(url);
            bis = new BufferedInputStream(is);
            bmp = BitmapFactory.decodeStream(bis);
        } catch (MalformedURLException e) {
            Log.e(TAG, "Bad ad URL", e);
        } catch (IOException e) {
            Log.e(TAG, "Could not get remote ad image", e);
        } finally {
            try {
                if (is != null)
                    is.close();
                if (bis != null)
                    bis.close();
            } catch (IOException e) {
                Log.w(TAG, "Error closing stream.");
            }
        }

        if (bmp == null) {
            url = URLFinder.randomURL();
        } else if (bmp.getWidth() > 1000 || bmp.getHeight() > 1000) {
            bmp = null;
            url = URLFinder.randomURL();
        }
    }

    appState.setURL(url);
    if (saveToHistory) {
        appState.getHistory().add(url);
        appState.setBackCursor(appState.getHistory().size() - 1);
    }

    if (!appState.getFavList().contains(appState.getURL())) {
        favButton.setBackgroundResource(android.R.drawable.btn_star);
    } else {
        favButton.setBackgroundResource(android.R.drawable.btn_star_big_on);
    }

    return bmp;
}

From source file:com.binroot.fatpita.BitmapManager2.java

/**
 * http://ballardhack.wordpress.com/2010/04/10/loading-images-over-http-on-a-separate-thread-on-android/
 * Convenience method to retrieve a bitmap image from
 * a URL over the network. The built-in methods do
 * not seem to work, as they return a FileNotFound
 * exception./*from w  ww .j  a  v a 2 s  .  c  o m*/
 *
 * Note that this does not perform any threading --
 * it blocks the call while retrieving the data.
 *
 * @param url The URL to read the bitmap from.
 * @return A Bitmap image or null if an error occurs.
 */
public Bitmap readBitmapFromNetwork(String url, int sample) {
    InputStream is = null;
    BufferedInputStream bis = null;
    Bitmap bmp = null;
    try {
        is = fetch(url);
        bis = new BufferedInputStream(is);

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = sample;
        bmp = BitmapFactory.decodeStream(bis, null, options);

    } catch (MalformedURLException e) {
        Log.e(TAG, "Bad ad URL", e);
    } catch (IOException e) {
        Log.e(TAG, "Could not get remote ad image", e);
    } finally {
        try {
            if (is != null)
                is.close();
            if (bis != null)
                bis.close();
        } catch (IOException e) {
            Log.w(TAG, "Error closing stream.");
        }
    }

    return bmp;
}

From source file:org.yawlfoundation.yawl.engine.interfce.Interface_Client.java

/**
 * Receives a reply from a HTTP submission
 * @param is the InputStream of a URL or Connection object
 * @return the stream's contents (ie. the HTTP reply)
 * @throws IOException when there's some kind of communication problem
 *///from  w w w  .ja v  a2 s  .  c om
private String getReply(InputStream is) throws IOException {
    final int BUF_SIZE = 16384;

    // read reply into a buffered byte stream - to preserve UTF-8
    BufferedInputStream inStream = new BufferedInputStream(is);
    ByteArrayOutputStream outStream = new ByteArrayOutputStream(BUF_SIZE);
    byte[] buffer = new byte[BUF_SIZE];

    // read chunks from the input stream and write them out
    int bytesRead;
    while ((bytesRead = inStream.read(buffer, 0, BUF_SIZE)) > 0) {
        outStream.write(buffer, 0, bytesRead);
    }

    outStream.close();
    inStream.close();

    // convert the bytes to a UTF-8 string
    return outStream.toString("UTF-8");
}

From source file:it.readbeyond.minstrel.librarian.FormatHandlerAbstractZIP.java

protected void extractCover(File f, Format format, String publicationID) {
    String destinationName = publicationID + "." + format.getName() + ".png";
    String entryName = format.getMetadatum("internalPathCover");

    if ((entryName == null) || (entryName.equals(""))) {
        format.addMetadatum("relativePathThumbnail", "");
        return;/*from   w ww .ja v a  2 s .c o  m*/
    }

    try {
        ZipFile zipFile = new ZipFile(f, ZipFile.OPEN_READ);
        ZipEntry entry = zipFile.getEntry(entryName);
        File destFile = new File(this.thumbnailDirectoryPath, "orig-" + destinationName);
        String destinationPath = destFile.getAbsolutePath();

        BufferedInputStream is = new BufferedInputStream(zipFile.getInputStream(entry));
        int numberOfBytesRead;
        byte data[] = new byte[BUFFER_SIZE];

        FileOutputStream fos = new FileOutputStream(destFile);
        BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER_SIZE);

        while ((numberOfBytesRead = is.read(data, 0, BUFFER_SIZE)) > -1) {
            dest.write(data, 0, numberOfBytesRead);
        }
        dest.flush();
        dest.close();
        is.close();
        fos.close();

        // create thumbnail
        FileInputStream fis = new FileInputStream(destinationPath);
        Bitmap imageBitmap = BitmapFactory.decodeStream(fis);
        imageBitmap = Bitmap.createScaledBitmap(imageBitmap, this.thumbnailWidth, this.thumbnailHeight, false);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] imageData = baos.toByteArray();

        // write thumbnail to file 
        File destFile2 = new File(this.thumbnailDirectoryPath, destinationName);
        String destinationPath2 = destFile2.getAbsolutePath();
        FileOutputStream fos2 = new FileOutputStream(destFile2);
        fos2.write(imageData, 0, imageData.length);
        fos2.flush();
        fos2.close();
        baos.close();

        // close ZIP
        zipFile.close();

        // delete original cover
        destFile.delete();

        // set relativePathThumbnail
        format.addMetadatum("relativePathThumbnail", destinationName);

    } catch (Exception e) {
        // nop 
    }
}

From source file:com.consol.citrus.report.HtmlReporter.java

/**
 * Reads citrus logo png image and converts to base64 encoded string for inline HTML image display.
 * @return/*from   ww  w. j  a  v a  2s  .  c om*/
 * @throws IOException 
 */
private String getLogoImageData() {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    BufferedInputStream reader = null;

    try {
        reader = new BufferedInputStream(logo.getInputStream());

        byte[] contents = new byte[1024];
        while (reader.read(contents) != -1) {
            os.write(contents);
        }
    } catch (IOException e) {
        log.warn("Failed to add logo image data to HTML report", e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException ex) {
                log.warn("Failed to close logo image resource for HTML report", ex);
            }
        }

        try {
            os.flush();
        } catch (IOException ex) {
            log.warn("Failed to flush logo image stream for HTML report", ex);
        }
    }

    return Base64.encodeBase64String(os.toByteArray());
}