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.freshplanet.ane.GoogleCloudStorageUpload.tasks.UploadToGoogleCloudStorageAsyncTask.java

private byte[] createHeaderByteArrayFile(byte[] prefix, byte[] suffix, String path) {
    Log.d(TAG, "[UploadToGoogleCloudStorageAsyncTask] Entering createHeaderByteArrayVideo()");

    File file = new File(path);
    int fileLength = (int) file.length();
    int size = fileLength + prefix.length + suffix.length;
    byte[] bytes = new byte[size];
    System.arraycopy(prefix, 0, bytes, 0, prefix.length);

    BufferedInputStream buf;
    try {//from ww  w  .j a  v a2s . c  o  m
        buf = new BufferedInputStream(new FileInputStream(file));
        buf.read(bytes, prefix.length, fileLength);
        buf.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    System.arraycopy(suffix, 0, bytes, fileLength + prefix.length, suffix.length);

    Log.d(TAG, "[UploadToGoogleCloudStorageAsyncTask] Exiting createHeaderByteArrayVideo()");
    return bytes;
}

From source file:gsn.wrappers.GPSGenerator.java

public boolean initialize() {
    AddressBean addressBean = getActiveAddressBean();
    if (addressBean.getPredicateValue("rate") != null) {
        samplingRate = ParamParser.getInteger(addressBean.getPredicateValue("rate"), DEFAULT_SAMPLING_RATE);
        if (samplingRate <= 0) {
            logger.warn(/*from  w ww .  j  a va2s .  c  o m*/
                    "The specified >sampling-rate< parameter for the >MemoryMonitoringWrapper< should be a positive number.\nGSN uses the default rate ("
                            + DEFAULT_SAMPLING_RATE + "ms ).");
            samplingRate = DEFAULT_SAMPLING_RATE;
        }
    }
    if (addressBean.getPredicateValue("picture") != null) {
        String picture = addressBean.getPredicateValue("picture");
        File pictureF = new File(picture);
        if (!pictureF.isFile() || !pictureF.canRead()) {
            logger.warn("The GPSGenerator can't access the specified picture file. Initialization failed.");
            return false;
        }
        try {
            BufferedInputStream fis = new BufferedInputStream(new FileInputStream(pictureF));
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[4 * 1024];
            while (fis.available() > 0)
                outputStream.write(buffer, 0, fis.read(buffer));
            fis.close();
            this.picture = outputStream.toByteArray();
            outputStream.close();
        } catch (FileNotFoundException e) {
            logger.warn(e.getMessage(), e);
            return false;
        } catch (IOException e) {
            logger.warn(e.getMessage(), e);
            return false;
        }
    } else {
        logger.warn("The >picture< parameter is missing from the GPSGenerator wrapper.");
        return false;
    }
    ArrayList<DataField> output = new ArrayList<DataField>();
    for (int i = 0; i < FIELD_NAMES.length; i++)
        output.add(new DataField(FIELD_NAMES[i], FIELD_TYPES_STRING[i], FIELD_DESCRIPTION[i]));
    outputStrcture = output.toArray(new DataField[] {});
    return true;
}

From source file:com.cubusmail.server.services.RetrieveImageServlet.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {//from   www  .j  av  a  2 s .c o m
        String messageId = request.getParameter("messageId");
        String attachmentIndex = request.getParameter("attachmentIndex");
        boolean isThumbnail = Boolean.valueOf(request.getParameter("thumbnail")).booleanValue();

        if (messageId != null) {
            IMailbox mailbox = SessionManager.get().getMailbox();
            Message msg = mailbox.getCurrentFolder().getMessageById(Long.parseLong(messageId));

            if (isThumbnail) {
                List<MimePart> attachmentList = MessageUtils.attachmentsFromPart(msg);
                int index = Integer.valueOf(attachmentIndex);

                MimePart retrievePart = attachmentList.get(index);

                ContentType contentType = new ContentType(retrievePart.getContentType());
                response.setContentType(contentType.getBaseType());

                BufferedInputStream bufInputStream = new BufferedInputStream(retrievePart.getInputStream());
                OutputStream outputStream = response.getOutputStream();

                writeScaledImage(bufInputStream, outputStream);

                bufInputStream.close();
                outputStream.flush();
                outputStream.close();
            } else {
                Part imagePart = findImagePart(msg);
                if (imagePart != null) {
                    ContentType contentType = new ContentType(imagePart.getContentType());
                    response.setContentType(contentType.getBaseType());

                    BufferedInputStream bufInputStream = new BufferedInputStream(imagePart.getInputStream());
                    OutputStream outputStream = response.getOutputStream();

                    byte[] inBuf = new byte[1024];
                    int len = 0;
                    int total = 0;
                    while ((len = bufInputStream.read(inBuf)) > 0) {
                        outputStream.write(inBuf, 0, len);
                        total += len;
                    }

                    bufInputStream.close();
                    outputStream.flush();
                    outputStream.close();
                }
            }
        }
    } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
    }
}

From source file:com.wavemaker.tools.util.TomcatServer.java

public String deploy(File war, String contextRoot) {

    if (war == null) {
        throw new IllegalArgumentException("war cannot be null");
    }//  w ww. j a  v  a2  s.  c o m

    if (!war.exists()) {
        throw new IllegalArgumentException("war does not exist");
    }

    if (war.isDirectory()) {
        throw new IllegalArgumentException("war cannot be a directory");
    }

    if (contextRoot == null) {
        contextRoot = StringUtils.fromFirstOccurrence(war.getName(), ".", -1);
    }

    contextRoot = checkContextRoot(contextRoot);

    if (isDeployed(contextRoot)) {
        undeploy(contextRoot);
    }

    String uri = getManagerUri() + "/deploy?" + getPathParam(contextRoot);

    HttpURLConnection con = super.getPutConnection(uri);

    con.setRequestProperty("Content-Type", "application/octet-stream");
    con.setRequestProperty("Content-Length", String.valueOf(war.length()));

    prepareConnection(con);

    try {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(war));
        BufferedOutputStream bos = new BufferedOutputStream(con.getOutputStream());
        IOUtils.copy(bis, bos);
        bis.close();
        bos.close();
    } catch (IOException ex) {
        throw new ConfigurationException(ex);
    }

    return ObjectUtils.toString(getResponse(con), "");
}

From source file:ca.licef.lompad.Classification.java

private String getQuery(String queryId, Object... params) throws java.io.IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    BufferedOutputStream bos = new BufferedOutputStream(baos);
    InputStream is = getClass().getResourceAsStream("/queries/" + queryId);

    BufferedInputStream bis = new BufferedInputStream(is);
    try {//from w w  w . java 2s  . c o  m
        IOUtil.copy(bis, bos);
    } finally {
        bis.close();
        bos.close();
    }
    String rawQuery = baos.toString("UTF-8");
    if (params == null || params.length == 0)
        return (rawQuery);

    String query = MessageFormat.format(rawQuery, params);
    return (query);
}

From source file:com.playhaven.android.diagnostic.test.PHTestCase.java

protected byte[] readFile(File file) throws IOException {
    PlayHaven.d("reading file: " + file.getAbsolutePath());
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
    ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
    byte[] buf = new byte[1024];
    int len;/* w ww. ja va  2  s  .  c om*/
    while ((len = in.read(buf)) != -1)
        out.write(buf, 0, len);

    out.flush();
    buf = out.toByteArray();
    in.close();
    out.close();
    return buf;
}

From source file:net.vexelon.bgrates.Utils.java

/**
 * Downloads a file given URL to specified destination
 * @param url/*from   w w w .  j  av  a 2 s. c  o m*/
 * @param destFile
 * @return
 */
//public static boolean downloadFile(Context context, String url, String destFile) {
public static boolean downloadFile(Context context, String url, File destFile) {
    //Log.v(TAG, "@downloadFile()");
    //Log.d(TAG, "Downloading " + url);

    boolean ret = false;

    BufferedInputStream bis = null;
    FileOutputStream fos = null;
    InputStream is = null;

    try {
        URL myUrl = new URL(url);
        URLConnection connection = myUrl.openConnection();

        is = connection.getInputStream();
        bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(1024);

        int n = 0;
        while ((n = bis.read()) != -1)
            baf.append((byte) n);

        // save to internal storage
        //Log.v(TAG, "Saving downloaded file ...");
        fos = new FileOutputStream(destFile);
        //context.openFileOutput(destFile, context.MODE_PRIVATE);
        fos.write(baf.toByteArray());
        fos.close();
        //Log.v(TAG, "File saved successfully.");

        ret = true;
    } catch (Exception e) {
        //Log.e(TAG, "Error while downloading and saving file !", e);
    } finally {
        try {
            if (fos != null)
                fos.close();
        } catch (IOException e) {
        }
        try {
            if (bis != null)
                bis.close();
        } catch (IOException e) {
        }
        try {
            if (is != null)
                is.close();
        } catch (IOException e) {
        }
    }

    return ret;
}

From source file:fi.mikuz.boarder.gui.ZipImporter.java

private void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException {

    File outputFile = new File(outputDir, entry.getName());

    if (entry.isDirectory()) {
        createDir(outputFile);/*from  ww w.j  av  a 2  s. c o m*/
        return;
    }

    if (!outputFile.getParentFile().exists()) {
        createDir(outputFile.getParentFile());
    }

    log = "Extracting: " + entry.getName() + "\n" + log;
    postMessage("Please wait\n\n" + log);
    Log.d(TAG, "Extracting: " + entry);
    BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry));
    BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));

    try {
        IOUtils.copy(inputStream, outputStream);
    } finally {
        outputStream.close();
        inputStream.close();
    }

}

From source file:de.uzk.hki.da.sb.restfulService.FileUtil.java

/**
 * <p><em>Title: Create a temporary File from a file identified by URL</em></p>
 * <p>Description: Method creates a temporary file from a remote file addressed 
 * an by URL representing the orginal PDF, that should be converted</p>
 * /*  w  ww .  j  ava 2  s . c o  m*/
 * @param fileName
 * @param url
 * @return 
 */
public static String saveUrlToFile(String fileName, String url) {

    String path = fileName.substring(0, fileName.lastIndexOf("/"));
    File dir = new File(Configuration.getTempDirPath() + "/" + path);
    dir.mkdirs();

    File inputFile = new File(Configuration.getTempDirPath() + "/" + fileName);
    InputStream is = null;
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    FileOutputStream fos = null;

    log.info(url);
    try {
        URL inputDocument = new URL(url);
        is = inputDocument.openStream();
        bis = new BufferedInputStream(is);

        fos = new FileOutputStream(inputFile);
        bos = new BufferedOutputStream(fos);
        int i = -1;
        while ((i = bis.read()) != -1) {
            bos.write(i);
        }
        bos.flush();
    } catch (Exception e) {
        log.error(e);
    } finally {
        if (bos != null) {
            try {
                bos.close();
            } catch (IOException ioExc) {
                log.error(ioExc);
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException ioExc) {
                log.error(ioExc);
            }
        }
        if (bis != null) {
            try {
                bis.close();
            } catch (IOException ioExc) {
                log.error(ioExc);
            }
        }
        if (is != null) {
            try {
                is.close();
            } catch (IOException ioExc) {
                log.error(ioExc);
            }
        }
    }

    return inputFile.getAbsolutePath();
}

From source file:net.firejack.platform.core.utils.ArchiveUtils.java

/**
  * @param basePath/*from   ww  w  . jav  a2 s. co m*/
  * @param tarPath
  * @param filePaths
  * @throws java.io.IOException
  */
public static void tar(String basePath, String tarPath, Map<String, String> filePaths) throws IOException {
    BufferedInputStream origin = null;
    TarArchiveOutputStream out = null;
    FileOutputStream dest = null;
    try {
        dest = new FileOutputStream(tarPath);
        out = new TarArchiveOutputStream(new BufferedOutputStream(dest));
        byte data[] = new byte[BUFFER];
        for (Map.Entry<String, String> entryFile : filePaths.entrySet()) {
            String filename = entryFile.getKey();
            String filePath = entryFile.getValue();
            System.out.println("Adding: " + filename + " => " + filePath);
            FileInputStream fi = new FileInputStream(basePath + filePath);
            origin = new BufferedInputStream(fi, BUFFER);
            TarArchiveEntry entry = new TarArchiveEntry(filename);
            out.putArchiveEntry(entry);
            int count;
            while ((count = origin.read(data, 0, BUFFER)) != -1) {
                out.write(data, 0, count);
            }
            origin.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (origin != null)
            origin.close();
        if (out != null)
            out.close();
        if (dest != null)
            dest.close();
    }
}