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:echopoint.tucana.FileDownloadProvider.java

/**
 * Writes the file data to the output stream.
 *
 * @param out the output stream to which the file data must be written.
 * @throws IOException If errors are encountered while writing the contents
 *   to the output stream./*from  www .ja  va  2  s . c o  m*/
 */
@SuppressWarnings({ "IOResourceOpenedButNotSafelyClosed" })
public void writeFile(final OutputStream out) throws IOException {
    status = Status.inprogress;

    try {
        final BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        IOUtils.copy(bis, out);
        out.flush();
        bis.close();
    } catch (IOException e) {
        status = Status.failed;
        throw e;
    }

    status = Status.completed;
}

From source file:com.dynamobi.network.DynamoNetworkUdr.java

/**
 * Fetches and stores a .jar file from a repo url/file-url, doing an md5sum check too.
 *///  w  w w  .j a v a2 s .  c o  m
private static void fetchJar(String url, String jarFile, String md5sum) throws SQLException {
    BufferedInputStream in = null;
    FileOutputStream out = null;
    try {
        String outfile = FarragoProperties.instance().expandProperties("${FARRAGO_HOME}/plugin/" + jarFile);
        in = new BufferedInputStream(new URL(url).openStream());
        out = new FileOutputStream(outfile);
        final int block_size = 1 << 18; // 256 kb
        byte data[] = new byte[block_size];
        int bytes;
        // for verifying md5
        MessageDigest dig = MessageDigest.getInstance("MD5");
        while ((bytes = in.read(data, 0, block_size)) != -1) {
            out.write(data, 0, bytes);
            dig.update(data, 0, bytes);
        }
        in.close();
        in = null;
        out.close();
        out = null;

        java.math.BigInteger biggy = new java.math.BigInteger(1, dig.digest());
        String md5check = biggy.toString(16);
        if (!md5sum.equals(md5check)) {
            throw new SQLException("Jar could not be fetched due to data mismatch.\n" + "Expected md5sum: "
                    + md5sum + "; got " + md5check);
        }
    } catch (Throwable e) {
        throw new SQLException(e);
    } finally {
        try {
            if (in != null)
                in.close();
            if (out != null)
                out.close();
        } catch (IOException e) {
            //pass
        }
    }
}

From source file:com.chinamobile.bcbsp.fault.tools.Zip.java

/**
 * Uncompress *.zip files./*w w  w  .j av a  2 s  . co  m*/
 * @param fileName
 *        : file to be uncompress
 */
@SuppressWarnings("unchecked")
public static void decompress(String fileName) {
    File sourceFile = new File(fileName);
    String filePath = sourceFile.getParent() + "/";
    try {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        ZipFile zipFile = new ZipFile(fileName);
        Enumeration en = zipFile.entries();
        byte[] data = new byte[BUFFER];
        while (en.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) en.nextElement();
            if (entry.isDirectory()) {
                new File(filePath + entry.getName()).mkdirs();
                continue;
            }
            bis = new BufferedInputStream(zipFile.getInputStream(entry));
            File file = new File(filePath + entry.getName());
            File parent = file.getParentFile();
            if (parent != null && (!parent.exists())) {
                parent.mkdirs();
            }
            bos = new BufferedOutputStream(new FileOutputStream(file));
            int count;
            while ((count = bis.read(data, 0, BUFFER)) != -1) {
                bos.write(data, 0, count);
            }
            bis.close();
            bos.close();
        }
        zipFile.close();
    } catch (IOException e) {
        //LOG.error("[compress]", e);
        throw new RuntimeException("[compress]", e);
    }
}

From source file:com.haoqee.chat.net.Utility.java

/**
 * Upload file into output stream ./*from   w  w  w  . j  ava2 s  .c om*/
 * 
 * @param out
 *            : output stream for uploading
 * @param file
 *            : file for uploading
 * @param filekey
 *            :uploaded files' key;
 * @return void
 */
private static void fileContentToUpload(OutputStream out, MorePicture filePath) throws ThinkchatException {
    StringBuilder temp = new StringBuilder();
    File file = new File(filePath.filePath);
    temp.append(MP_BOUNDARY).append("\r\n");
    temp.append(
            "Content-Disposition: form-data; name=\"" + filePath.key + "\"; filename=\"" + file.getName() + "")
            .append("").append("\"\r\n");
    byte[] fileData = getFileByte(file);
    String filetype = "multipart/form-data";

    temp.append("Content-Type: ").append(filetype).append("\r\n\r\n");
    byte[] res = temp.toString().getBytes();
    BufferedInputStream bis = null;
    try {
        out.write(res);
        out.write(fileData);
        // imgpath.compress(CompressFormat.PNG, 75, out);
        out.write("\r\n".getBytes());
        // out.write(("\r\n" + END_MP_BOUNDARY).getBytes());
    } catch (IOException e) {
        throw new ThinkchatException(e);
    } finally {
        if (null != bis) {
            try {
                bis.close();
            } catch (IOException e) {
                throw new ThinkchatException(e);
            }
        }
    }
}

From source file:com.research.net.Utility.java

/**
 * Upload file into output stream ./*from w  ww  .j  a  v a  2 s .c o  m*/
 * 
 * @param out
 *            : output stream for uploading
 * @param file
 *            : file for uploading
 * @param filekey
 *              :uploaded files' key;          
 * @return void
 */
private static void fileContentToUpload(OutputStream out, /*Bitmap imgpath*/File file, String key)
        throws ResearchException {
    StringBuilder temp = new StringBuilder();

    temp.append(MP_BOUNDARY).append("\r\n");
    /* temp.append("Content-Disposition: form-data; name=\"f_upload\"; filename=\"" + file.getName() + "")
        .append("").append("\"\r\n");*/
    temp.append("Content-Disposition: form-data; name=\"" + key + "\"; filename=\"" + file.getName())
            /*.append(key+".png")*/.append("").append("\"\r\n");
    byte[] fileData = getFileByte(file);
    String filetype = "multipart/form-data";

    temp.append("Content-Type: ").append(filetype).append("\r\n\r\n");
    byte[] res = temp.toString().getBytes();
    BufferedInputStream bis = null;
    try {
        out.write(res);
        out.write(fileData);
        //imgpath.compress(CompressFormat.PNG, 75, out);
        out.write("\r\n".getBytes());
        //out.write(("\r\n" + END_MP_BOUNDARY).getBytes());
    } catch (IOException e) {
        throw new ResearchException(e);
    } finally {
        if (null != bis) {
            try {
                bis.close();
            } catch (IOException e) {
                throw new ResearchException(e);
            }
        }
    }
}

From source file:de.petermoesenthin.alarming.util.FileUtil.java

/**
 * Copies a file to the Alarming directory in the external storage
 *
 * @param context Application context/*from w  w w .  j av  a  2 s .c om*/
 * @param uri     Uri of file to copy
 */
public static void saveFileToExtAppStorage(final Context context, final Uri uri,
        final OnCopyFinishedListener op) {
    final File applicationDirectory = getApplicationDirectory();
    if (!applicationDirectory.exists()) {
        applicationDirectory.mkdirs();
    }
    File noMedia = new File(applicationDirectory.getPath() + File.separatorChar + ".nomedia");
    if (!noMedia.exists()) {
        try {
            noMedia.createNewFile();
            Log.e(DEBUG_TAG, "Created .nomedia file in: " + noMedia.getAbsolutePath());
        } catch (IOException e) {
            Log.e(DEBUG_TAG, "Unable to create .nomedia file", e);
        }
    }

    String fileName = getFilenameFromUriNoSpace(uri);
    final File destinationFile = new File(applicationDirectory.getPath() + File.separatorChar + fileName);

    Log.d(DEBUG_TAG, "Source file name: " + fileName);
    Log.d(DEBUG_TAG, "Source file uri: " + uri.toString());
    Log.d(DEBUG_TAG, "Destination file: " + destinationFile.getPath());

    Thread copyThread = new Thread(new Runnable() {
        @Override
        public void run() {
            BufferedInputStream bis = null;
            BufferedOutputStream bos = null;
            if (isExternalStorageWritable()) {
                try {
                    InputStream uriStream = context.getContentResolver().openInputStream(uri);
                    bis = new BufferedInputStream(uriStream);
                    bos = new BufferedOutputStream(new FileOutputStream(destinationFile.getPath(), false));
                    byte[] buf = new byte[1024];
                    while (bis.read(buf) != -1) {
                        bos.write(buf);
                    }
                } catch (IOException e) {
                    Log.e(DEBUG_TAG, "Unable to copy file from URI", e);

                } finally {
                    try {
                        if (bis != null)
                            bis.close();
                        if (bos != null)
                            bos.close();
                    } catch (IOException e) {
                        Log.e(DEBUG_TAG, "Unable to close buffers", e);
                    }
                }
            }
            if (op != null) {
                op.onOperationFinished();
            }
        }
    });
    copyThread.start();
}

From source file:eu.learnpad.simulator.mon.utils.Manager.java

@SuppressWarnings("deprecation")
public static Properties Read(String fileName) {
    Properties readedProps = new Properties();

    File file = new File(fileName);
    FileInputStream fis = null;/* ww  w  .ja  va  2  s .co  m*/
    BufferedInputStream bis = null;
    DataInputStream dis = null;

    try {
        fis = new FileInputStream(file);

        // Here BufferedInputStream is added for fast reading.
        bis = new BufferedInputStream(fis);
        dis = new DataInputStream(bis);

        // dis.available() returns 0 if the file does not have more lines.
        String property = "";
        String key = "";
        String value = "";

        while (dis.available() != 0) {
            // this statement reads the line from the file and print it to
            // the console.
            property = dis.readLine().trim();
            if (property.length() > 0) {
                key = property.substring(0, property.indexOf("="));
                value = property.substring(property.indexOf("=") + 1, property.length());

                readedProps.put(key.trim(), value.trim());
            }
        }

        // dispose all the resources after using them.
        fis.close();
        bis.close();
        dis.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return readedProps;
}

From source file:com.nzion.web.PdfServlet.java

@Override
protected void service(HttpServletRequest reqqest, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/plm");
    response.setHeader("Content-Disposition", "attachment; filename=2D.plm");
    ServletOutputStream outputStream = response.getOutputStream();
    BufferedInputStream bufferedInputStream = new BufferedInputStream(
            new FileInputStream(new File("F:\\PDF_Stamping\\2D\\2D.zip")));
    IOUtils.copy(bufferedInputStream, outputStream);
    bufferedInputStream.close();
    outputStream.flush();//from   w w w  . j a v a2  s.  c om
}

From source file:com.yoctopuce.YoctoAPI.YFirmwareUpdate.java

static byte[] _downloadfile(String url) throws YAPI_Exception {
    ByteArrayOutputStream result = new ByteArrayOutputStream(1024);
    URL u = null;/*w  w w  . j ava 2s . c o m*/
    try {
        u = new URL(url);
    } catch (MalformedURLException e) {
        throw new YAPI_Exception(YAPI.IO_ERROR, e.getLocalizedMessage());
    }
    BufferedInputStream in = null;
    try {
        URLConnection connection = u.openConnection();
        in = new BufferedInputStream(connection.getInputStream());
        byte[] buffer = new byte[1024];
        int readed = 0;
        while (readed >= 0) {
            readed = in.read(buffer, 0, buffer.length);
            if (readed < 0) {
                // end of connection
                break;
            } else {
                result.write(buffer, 0, readed);
            }
        }

    } catch (IOException e) {
        throw new YAPI_Exception(YAPI.IO_ERROR,
                "unable to contact www.yoctopuce.com :" + e.getLocalizedMessage());
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ignore) {
            }
        }
    }
    return result.toByteArray();
}

From source file:eu.liveandgov.ar.utilities.Download_Data.java

/**                      DownAndCopy
 * //from w w  w  .j av  a  2s. co  m
 * Download file from URL and Copy to Android file system folder
 * 
 * @param fileUrl
 * @param StringAndroidPath
 */
public static boolean DownAndCopy(String fileUrlSTR, String StringAndroidPath, boolean preservefilename,
        String Caller) {

    if (compareRemoteWithLocal(fileUrlSTR, StringAndroidPath)) {
        //Log.e("fileUrlSTR", "SKIP WITH HASH");
        return true;
    } else {
        Log.e("TRY TO DOWNLOAD BY " + Caller, fileUrlSTR);
    }

    SimpleDateFormat sdf = new SimpleDateFormat("mm");

    // Check if downloaded at least just 2 minutes ago
    for (String[] mem : MemDown)
        if (fileUrlSTR.equals(mem[0])) {
            int diff = Integer.parseInt(sdf.format(new Date())) - Integer.parseInt(mem[1]);
            Log.e("diff", " " + diff);
            if (diff < 2) {
                Log.d("Download_Data", "I am not downloading " + fileUrlSTR + " because it was downloaded "
                        + diff + " minutes ago");
                return true;
            }
        }

    if (!OS_Utils.exists(fileUrlSTR)) {
        Log.e("Download_Data", "URL: " + fileUrlSTR + " called from " + Caller + " not exists to copy it to "
                + StringAndroidPath);
        return false;
    }

    int DEBUG_FLAG = 0;

    HttpURLConnection conn;
    URL fileUrl = null;
    try {
        fileUrl = new URL(fileUrlSTR);
    } catch (MalformedURLException e1) {
        return false;
    }

    try {
        conn = (HttpURLConnection) fileUrl.openConnection();

        DEBUG_FLAG = 1;

        conn.setDoInput(true);
        conn.connect();
        InputStream is = conn.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(100);

        DEBUG_FLAG = 2;

        int current = 0;
        byte[] buffer = new byte[10];
        while ((current = bis.read(buffer)) != -1)
            baf.append(buffer, 0, current);

        DEBUG_FLAG = 3;

        /* Convert the Bytes read to a String. */
        File fileAndroid;

        try {

            if (preservefilename) {
                int iSlash = fileUrlSTR.lastIndexOf("/");
                fileAndroid = new File(StringAndroidPath + "/" + fileUrlSTR.substring(iSlash + 1));
            } else
                fileAndroid = new File(StringAndroidPath);

        } catch (Exception e) {
            Log.e("Download_Data.DownAndCopy", "I can not create " + StringAndroidPath);
            bis.close();
            conn.disconnect();
            return false;
        }

        DEBUG_FLAG = 4;

        FileOutputStream fos = new FileOutputStream(fileAndroid);
        fos.write(baf.toByteArray());

        DEBUG_FLAG = 5;

        bis.close();
        fos.close();
        conn.disconnect();

        MemDown.add(new String[] { fileUrlSTR, sdf.format(new Date()) });

        return true; //returns including the filename
    } catch (IOException e) {
        Log.e("Download_Data", "Download_Data: Error when trying to download:  " + fileUrl.toString() + " to "
                + StringAndroidPath + " DEBUG_FLAG=" + DEBUG_FLAG);
        return false;
    }

}